272

Possible Duplicates:
Check if text is in a string
JavaScript: string contains

I'm trying to check if a string I import into my application has a certain piece of text. I know how to do this with jQuery, but how do I do it with straight up JavaScript?

2

1 Answer 1

488

Here you go: ES5

var test = 'Hello World';
if( test.indexOf('World') >= 0){
  // Found world
}

With ES6 best way would be to use includes function to test if the string contains the looking work.

const test = 'Hello World';
if (test.includes('World')) { 
  // Found world
}
Sign up to request clarification or add additional context in comments.

7 Comments

What if the string starts with "World"? The operator should probably be >= 0.
If I understand correctly, and >=0 value is a match
I like !== -1 better
I like if (~test.indexOf('World')) better
When to use ES6?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.