36

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.

1
  • Here a benchmark for the most common ways to check if a string is in a string: jsben.ch/#/o6KmH Commented Oct 31, 2016 at 17:06

5 Answers 5

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
Sign up to request clarification or add additional context in comments.

2 Comments

further to this answer, you could create function contains(haystack, needle) { return haystack.indexOf(needle) > -1; } Or even create one on the String prototype
@Jonathan I added a String.prototype function.
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

Comments

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.

3 Comments

although this works, val > -1 is fewer operations
@zzzzBov, technically the !! Is unnecesary. So just the tilde would work.
...depending on how strictly you need a boolean value. I agree, ~ will output the correct falsey state.
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' ]

Comments

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

2 Comments

I'm using JavaScript, but thanks :P
Even better: var regex = /Hello, my name is jonh/; regex.test("Hello, my name is jonh LOL."); // true

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.