Case-insensitive search

320,335

Solution 1

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');
}

Solution 2

Replace

var result= string.search(/searchstring/i);

with

var result= string.search(new RegExp(searchstring, "i"));

Solution 3

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;

Solution 4

Suppose we want to find the string variable needle in the string variable haystack. There are three gotchas:

  1. Internationalized applications should avoid string.toUpperCase and string.toLowerCase. Use a regular expression which ignores case instead. For example, var needleRegExp = new RegExp(needle, "i"); followed by needleRegExp.test(haystack).
  2. In general, you might not know the value of needle. Be careful that needle does not contain any regular expression special characters. Escape these using needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");.
  3. In other cases, if you want to precisely match needle and haystack, 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);

Solution 5

ES6+:

let string="Stackoverflow is the BEST";
let searchstring="best";


let found = string.toLowerCase()
                  .includes(searchstring.toLowerCase());

includes() returns true if searchString appears at one or more positions or false otherwise.

Share:
320,335

Related videos on Youtube

AntennaQuad
Author by

AntennaQuad

Updated on April 12, 2022

Comments

  • AntennaQuad
    AntennaQuad about 2 years

    I'm trying to get a case-insensitive search with two strings in JavaScript working.

    Normally it would be like this:

    var string="Stackoverflow is the BEST";
    var result= string.search(/best/i);
    alert(result);
    

    The /i flag would be for case-insensitive.

    But I need to search for a second string; without the flag it works perfect:

    var string="Stackoverflow is the BEST";
    var searchstring="best";
    var result= string.search(searchstring);
    alert(result);
    

    If I add the /i flag to the above example it would search for searchstring and not for what is in the variable "searchstring" (next example not working):

    var string="Stackoverflow is the BEST";
    var searchstring="best";
    var result= string.search(/searchstring/i);
    alert(result);
    

    How can I achieve this?

  • Dan
    Dan over 15 years
    That's a rather messy way around it, as it takes to measures to guard against unexpected regexp metacharacters.
  • Sergey Ilinsky
    Sergey Ilinsky over 15 years
    Dan, I doubt my answer deserves -1 from you. I tried helping ChrisBo by correcting his improper usage of JavaScript, namely: var result= string.search(/searchstring/i); to a proper one, where variable searchstring was used the way he intended.
  • glenn jackman
    glenn jackman over 14 years
    Dan's right (though he probably meant to say "no measures"): s = 'a[b'; r = new RegExp(s) results in a syntax error (unterminated character class)
  • Doug Molineux
    Doug Molineux over 8 years
    Sorry how can you convert "best" into a variable in your first example? string.match(/best/i);
  • Rami
    Rami over 8 years
    Why would you use .match for boolean comparison. It searches beyond the first result. You need to stop after first match which .test or .search do. Check performance here.
  • Ohad Schneider
    Ohad Schneider almost 8 years
    toLowerCase will most likely fail the Turkey Test (moserware.com/2008/02/does-your-code-pass-turkey-test.html) and similar case conversion issues. I'm not sure how ReGex handles it, but if I had to guess I'd say better.
  • Medeni Baykal
    Medeni Baykal over 5 years
    @DougMolineux you can use the RegExp object constructor. var text = "best"; var exp = new RegExp(test, "i");. This is same as /best/i.