Tuesday, December 11, 2018

How to check whether a string contains a substring in JavaScript?





Usually I would expect a String.contains() method, but there doesn't seem to be one.



What is a reasonable way to check for this?


Answer



ECMAScript 6 introduced String.prototype.includes:





var string = "foo",
substring = "oo";


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





includes doesn’t have Internet Explorer support, though. In ECMAScript 5 or older environments, use String.prototype.indexOf, which returns -1 when a substring cannot be found:






var string = "foo",
substring = "oo";

console.log(string.indexOf(substring) !== -1);




No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...