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

No comments yet. Be the first to leave a comment!

Leave a Comment

Your email address will not be published. Required fields are marked *