views:

10093

answers:

4
+12  A: 

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');
}
Dan
What if matchString has value of "bEst"? The proper case-insensitive search should still find the occurrence. In your case you would probably also need to call toLowerCase() on the search term as well.
Sergey Ilinsky
I added a comment to reflect that fact, thanks.
Dan
+5  A: 

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

replace with:

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

Sergey Ilinsky
That's a rather messy way around it, as it takes to measures to guard against unexpected regexp metacharacters.
Dan
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.
Sergey Ilinsky
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)
glenn jackman
+1  A: 

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;
Odilon Redo
A: 

If you are concerned about the "unterminated character class" case, removing all non-alphanumeric chars would be helpful:

searchstring = searchstring.replace(/[^a-zA-Z 0-9]+/g,'');