How to Check If a String Contains Another Substring in JavaScript

Checking whether a string contains another string or not is very common in JavaScript and as well as in other programming languages. Several methods are used to check if a string contains another substring in Javascript. Let's discuss one of the most common tasks bellow.

String.includes()

This String.includes() method searches the sequence of characters in the string and returns true if a sequence of char value exists, otherwise returns false:

Javascript String.includes method searches the sequence of characters in the string
const string = "W3Docs"; const substring = "W3"; console.log(string.includes(substring));

String.indexOf

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

Javascript string.indexOf method returns the position of the value's first occurrence in a string
let string = "W3Docs"; let substring = "Docs"; console.log(string.indexOf(substring));
Both the string.includes() and string.indexof() methods are case sensitive.

Regex

RegExp provides more flexibility. To check for substrings in a string with regex can be done with the test() method of regular expression. This method is much easier to use as it returns a boolean. It returns direct true or false results compared to the indexOf() method, therefore, be a good alternative:

Javascript test method check for substrings in a string with regex
let str = 'stackabuse'; console.log(/stack/.test(str));

The test() method searches for a match between a RegExp and a specified string, thus returning true if the string is present; otherwise, it returns false.