1. Introduction
In this short article, we are going to show a method to check whether one string contains another in JavaScript.
2. Using indexof()
method
The one method comes from the original vanilla JS. We can simply use indexOf()
function on String
object that takes the substring value to search for.
var string = "foo";
var substring = "oo";
console.log(string.indexOf(substring) !== -1); // true
console.log(string.indexOf("foof") !== -1); // false
3. Using includes()
method from ES6
ES6 comes with the function includes()
that determines whether one string may be found within another.
const string = "foo";
const substring = "oo";
console.log(string.includes(substring)); // true
console.log(string.includes("foof")); // false
4. Polyfill of includes()
method
If you want to be 100% sure that includes()
method will be available on all browsers you can add polyfill that could look like the following:
5. Conclusion
In this article, we showed a way to check if one string may be found within another string. We used indexOf
method and includes()
that was introduced in ECMAScript 6.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}