Check if a string has a certain piece of text

JavascriptString

Javascript Problem Overview


> 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?

Javascript Solutions


Solution 1 - Javascript

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
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionswickbladeView Question on Stackoverflow
Solution 1 - JavascriptEddieView Answer on Stackoverflow