Introduction
Sometimes, we want to check if a string contains a substring in JavaScript.
In this post, we'll present how to check if a string contains a substring in JS.
How to check whether a string contains a substring in JavaScript
To check if a string contains a substring in JavaScript we use string.indexOf(...)
method:
If string.indexOf(substring)
is equal to -1
it means that string doesn't contain given substring.
So to check if string contains another string we need to negate this condition: string.indexOf(substring) !== -1
.
Conclusion
To check if string contains a substring we use string.indexOf(substring)
method.
In ES6 we can use string.includes(substring) method to check if string contains another string.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}