There are a number of ways you could approach this problem. We’ll take a look at two methods:
includes() method to check whether a string contains a substring. This will return
true if the substring is found, or
false if not.
Consider the code example below:
const str = 'This is my example string!'; const substr = 'my'; console.log(str.includes(substr));
The above code would output
includes() performs a case-sensitive search. To work around this, you can convert the string to lower case using
toLowerCase() as follows:
position can also be passed as an argument to specify the position at which to begin searching the string for the substring. The default position is
0. If you want to begin searching at position
2, you would write:
indexOf() method is also case sensitive, and returns the index position of the first occurrence of the substring within the string. If the substring is not found, it returns
const str = 'This is my example string!'; const substr = 'my'; console.log(str.indexOf(substr));
The code above returns
You can also include the
position at which to begin searching the string for the substring. The default position is
Other search methods you can consider include:
search(regExp)– Returns the index of the first match between
regExpand the string. If no match is found,
lastIndexOf(searchValue)– Returns the index position of the last occurrence of
searchValueinside a string.
match(searchValue)– Finds the
searchValue, a regular expression, within a given string and returns an array containing the matches.
charAt(index)– Returns a string representing the character at the specified index. If the index is out of range, it returns an empty string.
searchValueis found at the beginning of a string.
falseif a string ends with the