Case-insensitive search
Yeah, use .match
, rather than .search
. The result from the .match
call will return the actual string that was matched itself, but it can still be used as a boolean value.
var string = "Stackoverflow is the BEST";
var result = string.match(/best/i);
// result == 'BEST';
if (result){
alert('Matched');
}
Using a regular expression like that is probably the tidiest and most obvious way to do that in JavaScript, but bear in mind it is a regular expression, and thus can contain regex metacharacters. If you want to take the string from elsewhere (eg, user input), or if you want to avoid having to escape a lot of metacharacters, then you're probably best using indexOf
like this:
matchString = 'best';
// If the match string is coming from user input you could do
// matchString = userInput.toLowerCase() here.
if (string.toLowerCase().indexOf(matchString) != -1){
alert('Matched');
}
Suppose we want to find the string variable needle
in the string variable haystack
. There are three gotchas:
- Internationalized applications should avoid
string.toUpperCase
andstring.toLowerCase
. Use a regular expression which ignores case instead. For example,var needleRegExp = new RegExp(needle, "i");
followed byneedleRegExp.test(haystack)
. - In general, you might not know the value of
needle
. Be careful thatneedle
does not contain any regular expression special characters. Escape these usingneedle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
. - In other cases, if you want to precisely match
needle
andhaystack
, just ignoring case, make sure to add"^"
at the start and"$"
at the end of your regular expression constructor.
Taking points (1) and (2) into consideration, an example would be:
var haystack = "A. BAIL. Of. Hay.";
var needle = "bail.";
var needleRegExp = new RegExp(needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "i");
var result = needleRegExp.test(haystack);
alert(result);
If you're just searching for a string rather than a more complicated regular expression, you can use indexOf()
- but remember to lowercase both strings first because indexOf()
is case sensitive:
var string="Stackoverflow is the BEST";
var searchstring="best";
// lowercase both strings
var lcString=string.toLowerCase();
var lcSearchString=searchstring.toLowerCase();
var result = lcString.indexOf(lcSearchString)>=0;
alert(result);
Or in a single line:
var result = string.toLowerCase().indexOf(searchstring.toLowerCase())>=0;
Replace
var result= string.search(/searchstring/i);
with
var result= string.search(new RegExp(searchstring, "i"));