Advertisement
Advertisement


Check if a string has a certain piece of text


Question

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?

2017/11/20
1
191
11/20/2017 3:02:14 PM

Accepted Answer

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
}
2018/11/01
344
11/1/2018 2:36:42 PM

Source: https://stackoverflow.com/questions/6629728
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]