W3docs

How to Check If a String Contains Another Substring in JavaScript

Read this tutorial and learn several methods used to check if a string contains another substring in JavaScript or not. Read information and see examples.

Checking whether a string contains another string is very common in JavaScript and other programming languages. Several methods can be used to check if a string contains a substring in JavaScript. Let's discuss the most common approaches below.

String.includes()

The includes() method searches for a sequence of characters in the string and returns true if the sequence exists, otherwise false:

JavaScript String.includes method searches for a sequence of characters in the string

javascript— editable

String.indexOf

The indexOf() method returns the position of the given value's first occurrence in a string. The method tests whether a substring exists. If it is present, it will return the starting index of the substring; otherwise, it will return -1:

JavaScript string.indexOf method returns the position of the value's first occurrence in a string

javascript— editable
Info

Both the <kbd class="highlighted">string.includes()</kbd> and <kbd class="highlighted">string.indexOf()</kbd> methods are case sensitive. Note that includes() is generally preferred for simple boolean checks.

Regex

RegExp provides more flexibility. Checking for substrings using regular expressions can be done with the test() method. This method is convenient because it returns a boolean. It provides direct true or false results, making it a good alternative to <kbd class="highlighted">indexOf()</kbd>:

JavaScript test method checks for substrings in a string using regex

javascript— editable

The <kbd class="highlighted">test()</kbd> method searches for a match between a RegExp and a specified string, returning true if the pattern is found; otherwise, it returns false.