35

Possible Duplicate:
JavaScript: string contains

I'm looking for an algorithm to check if a string exists in another.

For example:

'Hello, my name is jonh LOL.'.contains('Hello, my name is jonh'); //true
'LOL. Hello, my name is jonh'.contains('Hello, my name is jonh'); //true

Thanks in advance.

Community
  • 1
  • 1
The Mask
  • 17,007
  • 37
  • 111
  • 185

5 Answers5

28

Use indexOf:

'Hello, my name is jonh LOL.'.indexOf('Hello, my name is jonh') > -1; //true
'LOL. Hello, my name is jonh'.indexOf('Hello, my name is jonh') > -1; //true

You can also extend String.prototype to have a contains function:

String.prototype.contains = function(substr) {
  return this.indexOf(substr) > -1;
}
'Hello, my name is jonh LOL.'.contains('Hello, my name is jonh'); //true
'LOL. Hello, my name is jonh'.contains('Hello, my name is jonh'); //true
Digital Plane
  • 37,354
  • 7
  • 57
  • 59
1

As Digital pointed out the indexOf method is the way to check. If you want a more declarative name like contains then you can add it to the String prototype.

String.prototype.contains = function(toCheck) {
  return this.indexOf(toCheck) >= 0;
}

After that your original code sample will work as written

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
1

How about going to obscurity:

!!~'Hello, my name is jonh LOL.'.indexOf('Hello, my name is jonh'); //true
if(~'LOL. Hello, my name is jonh'.indexOf('Hello, my name is jonh'))
    alert(true);

Using Bitwise NOT and to boolean NOTs to convert it to a boolean than convert it back.

Joe
  • 80,724
  • 18
  • 127
  • 145
0

I would suppose that using pre-compiled Perl-based regular expression would be pretty efficient.

RegEx rx = new Regex('Hello, my name is jonh', RegexOptions.Compiled);
rx.IsMatch('Hello, my name is jonh LOL.'); // true
clarkb86
  • 673
  • 5
  • 21
0

another option could be to match a regular expression by using match(): http://www.w3schools.com/jsref/jsref_match.asp.

> var foo = "foo";
> console.log(foo.match(/bar/));
null
> console.log(foo.match(/foo/));
[ 'foo', index: 0, input: 'foo' ]
marcelog
  • 7,062
  • 1
  • 33
  • 46