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.
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:
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:
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:
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.