Anjan Dutta
Check if string contains substring javascript
Check if string contains substring javascript
How to check if string contains substring in javascript is a frequent and common problem that we get often.
In this article, I am going to discuss two related things.
- Check if string contains substring javascript.
- Find the number of occurrences of a substring within a string.
Playing with string is interesting plus a bit tricky. Tricky because of the case sensitiveness of strings.
So, if it is not necessary to maintain the case of a given string, then convert both the sides of the problem to a common format. I always convert strings to lowercase before comparing.
Check if string contains substring javascript
In the new version of Javascript (ES6), we can use the .includes()
function to check whether a string contains a substring or not.
The code looks like below.
const sentence= "The quick brown fox jumped over";const needle= "fox";console.log(string.includes(needle)); // true
For older browser support (IE)
Old browser like the Internet Explorer does not support the includes property. To support IE, we can use the .indexOf()
function.
The .indexOf()
function returns a number indicating the index of a substring in a given string. If the substring is not present, then it will return -1.
The solution looks like below.
var sentence= "The quick brown fox jumped over";var needle= "fox";console.log(sentence.indexOf(substring) !== -1); //true
Find the number of occurrences of a substring within a string
To find the number of occurrences of a substring within a string, we will use the .match()
function. The .match()
function takes one parameter, a regex string.
Check the below example.
var sentence= "The quick brown fox jumped over the lazy dog";var occurrances = (sentence.toLowerCase().match(/the/g) || []).length;console.log(occurrances ); //2
In the above example, we are trying to find 'the'
in the given sentence.
Now, the given sentence contains ‘The’ and 'the' which is not the same. So, in the second line, we have written sentence.toLowerCase()
to convert the sentence to lowercase first. Which would look like below.
the quick brown fox jumped over the lazy dog
then we have applied the .match(/the/g)
function, to check the number of occurrences. You can replace /the/
with any other string to check accordingly.