Sometimes, we may want to check if a substring is in a JavaScript string in a case-insensitive manner.
In this article, we’ll check if a JavaScript string has a substring in a case-insensitive manner.
String.prototype.toLowerCase and String.prototype.indexOf
We can convert both the string and the substring we’re checking for the lower case to check if a substring is in a JavaScript string is in a case-insensitive manner.
For instance, we can write:
const includes = 'ABCDE'.toLowerCase().indexOf("abc".toLowerCase()) !== -1
console.log(includes)
We call toLowerCase on 'ABCDE' and 'abc' to convert them both to lower case.
And then we call indexOf to check if “abc”.toLowerCase() to if included in 'ABCDE' in a case-insensitive manner.
Since 'abc' is in 'ABCDE' when they’re compared in a case-insensitive manner, indexOf should return an index other than -1.
And so includes is true .
Case-Insensitive Regex Search
We can also do a case-insensitive regex search in our code.
For instance, we can write:
const includes = /abc/i.test('ABCDE')
console.log(includes)
The i flag lets us search for a pattern in the string we pass into test in a case-insensitive manner.
And so includes is also true in this example.
Case-Insensitive Regex Search with RegExp Constructor
Alternatively, we can do a case-insensitive regex search with the RegExp constructor.
For instance, we can write:
const includes = new RegExp("abc", "i").test('ABCDE')
console.log(includes)
to do the same as we did before.
String.prototype.toLowerCase and String.prototype.includes
We can also substitute the indexOf method in the first example with includes .
Using the includes method, we don’t have to compare against -1.
Instead, we get true if the substring is included in a string and false otherwise.
So we can write:
const included = 'ABCDE'.toLowerCase().includes("abc".toLowerCase())
console.log(included)
We convert them both the string and substring to lower case as usual, but we use includes to check if the substring we pass into includes is included in 'ABCDE' .
And so we should get the same result as before.
String.prototype.toLocaleLowerCase and String.prototype.includes
If we’re checking a JavaScript substring with a string that has text other than English, we may want to use the toLocaleLowerCase method since it works with non-English locales.
For instance, we can write:
const included = 'ABCDE'.toLocaleLowerCase().includes("abc".toLocaleLowerCase())
console.log(included)
And we get the same result as before.
Conclusion
We can use various string or regex methods to check whether a substring is included in a JavaScript string in a case insensitive manner.
One reply on “How to Check if a JavaScript String Contains a Substring in a Case Insensitive Manner?”
Perfect idea, tahnks