JavaScript – Check if String contains a substring

In JavaScript, we can use the classic indexOf() or the new ES6 includes to check if a String contains a substring.


        // old school, classic way
        var str = "mkyong";
        if (str.indexOf('yo') > -1) { // returns `-1` if it is not present.
            console.log('match') // display this
        } else {
            console.log('not found')
        }

        // ES6 only
        var str = "mkyong";
        console.log(str.includes('mk')); //true
        console.log(str.includes('mkg'));//false

References

Image

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments