When we create a string searching utility, for example, what we are actually trying to accomplish under the hood is to check if a string contains a substring. There are several ways we can implement this functionality in javascript. So, let us now discuss how to check if a string contains a substring in javascript.

Check if a string contains a substring in JavaScript

Depending on the application, we might just want to know whether a substring can be found within another string, without bothering about the position at which it occurs. This section explores the ways we can do this in JavaScript.

Check at beginning or end of text – startsWith() and endsWith()

First, we might need to be specific with our search by checking if the string has a match that starts at the first characters of the text. Javascript provides the string.startsWith() method. The method just needs the string we are searching for as an input, and it will then return a boolean indicating whether the string we searched for occurred at the head of the text string or not.


const sentence = "The quick brown fox jumps over the lazy dog";

console.log(sentence.startsWith("he"));     // will return false
console.log(sentence.startsWith("The"));    // will return true
console.log(sentence.startsWith("the"));    // will return false

The search is case-sensitive, that is why the last console.log() function returned false.

We can also fine-tune the search by also telling startsWith() the index at which to begin searching. When we do not specify the index, an index of 0 is assumed.


const sentence = "The quick brown fox jumps over the lazy dog";

console.log(sentence.startsWith("he", 1));     // will now return true
console.log(sentence.startsWith("The", 31));    // will now return false
console.log(sentence.startsWith("the", 31));    // will now return true

Similar to startsWith(), we have the string.endsWith() method. endsWith() has similar behaviour to startsWith(), but it checks if a string ends with another string.


const sentence = "The quick brown fox jumps over the lazy dog";

console.log(sentence.endsWith("dog"));      // will return true
console.log(sentence.endsWith("Dog"));      // will return false
console.log(sentence.endsWith("do"));       // will return false

The last two console.log() calls returned false since

  • The substring "Dog" has a different character casing from the substring "dog".
  • The substring "do" does not match at the end of the string sentence

If we want to successfully match the substring "do", we need to tell endsWith() what portion of the string do we need to search? sentence has 43 characters, and "do" matches at the 42nd character. So, that is the portion of the string we will tell endsWith() to match.


console.log(sentence.endsWith("do", 42));       // will return true

In contrast to string.startsWith() where we could specify a start index, endsWith() allows us to specify a length – the portion of the string to concentrate our search on.

In summary, string methods startsWith() and endsWith() try to check if substrings occur at the start, or end, of a given string object. If the match occurs at the beginning, or end, of the string searched, they return true, otherwise, false is returned.

If we do not want to bother about occurrences at the start or end of the string we are searching, but instead allow the match to occur anywhere within the string, we can make use of the string.includes() method.

Check throughout a string using includes()

With this method, we can find out whether or not a substring has a match within the string. It is also case sensitive like startsWith() and endsWith(). The following example will illustrate this.


const sentence = "The quick brown fox jumps over the lazy dog";

console.log(sentence.includes("quick"));        // will return true
console.log(sentence.includes("Quick"));        // will return false

We can also state the position we want our search to begin. If we do not specify any start index, includes() will assume a start index of 0. That means, for example, includes("quick") will behave similarly to includes("quick", 0). In the next example, we will specify a start position while searching for "The" within sentence.


console.log(sentence.includes("The", 0));     // will return true
console.log(sentence.includes("The", 1));     // will return false

The second attempt to find "The" within sentence failed because we started our search at index 1. At that position, and moving left to right, we cannot match "The" within sentence anymore.

Check for the position at which a substring can be found within a string – indexOf() and lastIndexOf()

The previous methods just gave a yes | no answer to whether a substring can be found within a string. If we need to know what position we can find a substring within a string, we can make use of the string methods indexOf() and lastIndexOf(). This section will discuss how to make use of these string methods.

indexOf() checks if a string contains a given substring, and returns the index of the first occurrence of the substring. If a match is not found, it returns -1. Also, the method is case-sensitive like the previous methods we have touched on.

In the following example, we will make use of a different string entirely to demonstrate how to make use of indexOf(). The string we will use will contain multiple occurrences of a particular word.


const rosySentence = "A Rose is a rose is a rose";

console.log(rosySentence.indexOf("Rose"));      // will return 2
console.log(rosySentence.indexOf("ROSE"));      // will return -1
console.log(rosySentence.indexOf("rose"));      // will return 12

indexOf() returned -1 while trying to check if the rosySentence contained "ROSE". This example was included to demonstrate that indexOf() is actually case-sensitive. The other calls to the method returned the positions of the first occurrence of the search item.

Notice that even if a substring occurs more than once in a string, indexOf() will only return the position where the first match was found. If we want to find matches beyond the first match, we will need a way to tell indexOf() to start searching after the position at which the first match was found. indexOf() actually allows us to specify a position to start our search.

So, for instance, if we started our search at position 13 (after the position of the first match) we will be able to find the second match. We will prove this with a second example.


const rosySentence = "A Rose is a rose is a rose";

console.log(rosySentence.indexOf("rose"));      // will return 12
console.log(rosySentence.indexOf("rose", 13));  // will return 22
console.log(rosySentence.indexOf("rose", 23));  // will return -1

The final call to indexOf() specified a start index of 23 (which is after the second match of "rose"). The call did not find any occurrences after that position, so it returned -1.

lastIndexOf() checks if a string contains a substring, but searches the entire string from the end of the string. In this sense, it is similar to string.endsWith(), but it returns the position at which the substring was found, or -1 if it was not found. Also, like previous methods, it is case-sensitive.

The next example demonstrates how to use lastIndexOf() to search for a substring within our rosySentence string.


const rosySentence = "A Rose is a rose is a rose";

console.log(rosySentence.lastIndexOf("Rose"));      // will return 2
console.log(rosySentence.lastIndexOf("ROSE"));      // will return -1
console.log(rosySentence.lastIndexOf("rose"));      // will return 22

The first call to lastIndexOf() returned the position of the only occurrence of "Rose" within rosySentence. Of course, "ROSE" is not contained in rosySentence, that is why lastIndexOf() returns -1.

We can also make lastIndexOf() to search for other occurrences of "rose" by giving it a start index. When not specified, a start index of rosySentence.length is assumed.


const rosySentence = "A Rose is a rose is a rose";

console.log(rosySentence.lastIndexOf("rose", 26));      // will return 22
console.log(rosySentence.lastIndexOf("rose", 21));      // will return 12
console.log(rosySentence.lastIndexOf("rose", 11));      // will return -1

The first call to lastIndexOf() uses a start index of 26 (which is the length of rosySentence). This call returns an index of 22, which is the last index where "rose" occurs.

The second call has to use a start index of 21 if we want to have any success in finding the next occurrence. We successfully find another occurence at index 12.

The last call starts at 11, and returns -1, since it can no longer find any occurrences of "rose" before index 11.

So far, we have been trying to find out if a string contains another substring specified exactly. In the sections that follow, we will try to carry out more complex searches using regular expressions.

Check if a string contains a substring in javascript – specify regular expression

Javascript also provides a way to do substring search by specifying a regular expression, or regex. This allows for more powerful checking capabilities. One string method to do this with isstring.search() method.

search() is similar to indexOf(); it searches the whole string from left to right and returns an index representing the position of the first match in the string.

However, we cannot give it a start index to restrict its search.

Another difference is that the string we are searching for has to be specified as a regular expression.

We will clarify by means of an example. Our example changes the sentence into a question having several repeating words and then tries to find the substring "feed" within it.


const question = "Is it OK to feed my dog the same thing that I feed my cat?"

console.log(question.search(/feed/));       // will return 12
console.log(question.search(/Feed/));       // will return -1

The example shows two different calls to search(). We passed the search item into each call as a regular expression. If instead, we give a string as a search item, string.search() will simply convert it into a regular expression.

The first call to search() successfully finds a match at position 12, which happens to be the first occurrence of the substring "feed". The next call fails, however, because search() is also case-sensitive. We can make search() to ignore case sensitivity by adding the ignore flag i.


const question = "Is it OK to feed my dog the same thing that I feed my cat?"

console.log(question.search(/feed/));       // will return 12
console.log(question.search(/Feed/i));      // will now return 12 because search is not case sensitive

Conclusion

That’s been it for our exploration into how to check if a string contains a substring in JavaScript.

We hope you could apply something from these tutorials to your coding exercises.

Keep learning, and check out our other javascript tutorials.

Like this article? Follow us on Facebook and LinkedIn.