JavaScript - Strings

Locate a string in another string

ES6

ECMAScript 6 introduced String.prototype.includes:

1
2
3
4
const string = "foo";
const substring = "oo";

console.log(string.includes(substring)); // true

ES5

In ECMAScript 5 or older environments, use String.prototype.indexOf, which returns -1 when a substring cannot be found:

1
2
3
4
5
var string = "foo";
var substring = "oo";

console.log(string.indexOf(substring) !== -1); // true
Run code snippet