Wednesday, 29 July 2015

How can I check if one string contains another substring?

In ES5

indexOf returns the position of the string in the other string. If not found, it will return -1:

    var s = "foo";
    alert(s.indexOf("oo") > -1);
 

In ES6 there are three new methods includes(), startsWith(), endsWith()

 var msg = "Hello world!";

 console.log(msg.startsWith("Hello"));       // true
 console.log(msg.endsWith("!"));             // true
 console.log(msg.includes("o"));             // true

 console.log(msg.startsWith("o", 4));        // true
 console.log(msg.endsWith("o", 8));          // true
 console.log(msg.includes("o", 8));          // false
 

No comments:

Post a Comment