Assuming we have a variable string that contains text (ie, it isn’t a number or another data type) we can check if string is equal to some text by using the === operator (when using text we need to remember to add apostrophes to indicate that it’s not code).

if (string === 'Hello World') {
  // Code here is run if string is equal to 'Hello World'
}

But perhaps string is a long paragraph of text and we want to check if it contains a certain word. To do this we can look for the location of that word within the paragraph (ie, its index). To do this we can use the indexOf() function in JavaScript. If we are able to find the location then indexOf() will return a positive number that represents the position of the word within a paragraph. However, if the word is not used in the paragraph then indexOf() returns a value of -1.

So to check if a word is used in a paragraph we check if it’s index is not equal to -1.

var string = 'Hello World';

if (string.indexOf("World") !== -1) {
  // Data contains the word 'World'
}
Was this article helpful?
YesNo