Reputation: 583
How i can search word in string ?
Example
var string="Stackoverflow is the BEST";
if i search 'BEST' it should return true
if i search 'is' it should return true
if i search 'bEST' it should return true
if i search 'BES' it should return false
if i search 'flow' it should return false
I have tried the following:
match()
search()
indexof()
How i can do it? thanks
Upvotes: 0
Views: 884
Reputation: 583
\b
is a word boundary character in a regular expression. /i
is ignore case. Replace best with your search word.
var string="Stackoverflow is the BEST";
var searchText = "Stackoverflow";
var re = new RegExp("\\b"+searchText+"\\b",'i');
if ( re.test(string)){
alert('match');
}else {
alert('not match');
}
Upvotes: 2
Reputation: 15148
I know this is a bit more verbose, but why not something like:
var exists = function (content, q) {
var result = content.split(" ").filter(function(item) {
return item.toLowerCase() === q.toLowerCase();
});
return result.length > 0;
};
Here is the fiddle.
Upvotes: 0
Reputation: 32066
Use a regex check. Google for word boundaries to learn more about them.
/\bbest\b/i.test("Stackoverflow is the BEST")
\b
is a word boundary character in a regular expression. /i
is ignore case. Replace best
with your search word.
Upvotes: 1
Reputation: 11116
use .test()
var string="Stackoverflow is the BEST";
var result= /s/i.test(string);
alert(result);
Upvotes: -1