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

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments