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