Muhammad Rashid
Muhammad Rashid

Reputation: 583

Javascript Search word in String not working

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

http://jsfiddle.net/FxV53/3/

Upvotes: 0

Views: 884

Answers (4)

Muhammad Rashid
Muhammad Rashid

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

Fiddle

Upvotes: 2

Dimitar Dimitrov
Dimitar Dimitrov

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

Andy Ray
Andy Ray

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

aelor
aelor

Reputation: 11116

use .test()

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

Upvotes: -1

Related Questions