JavaScript – How to check whether a string contains a sub-string

JavaScript

Deprecated: get_the_author_email is deprecated since version 2.8.0! Use get_the_author_meta('email') instead. in /home/cloudber/public_html/wp-includes/functions.php on line 4713

1. String indexOf()

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

var haystack = "foo", needle = "oo";
haystack.indexOf(needle) !== -1; //Output: true

2. String includes()

Starting from ES6, includes() determines whether one string may be found within another string, returning true or false as appropriate.

var haystack = "foo", needle = "oo";
haystack.includes(needle); //Output: true

3. Regex test()

var haystack = "foo",
expr = /oo/; // quotes not needed
expr.test(haystack); //Output: true

If it comes to a point where speed matters. indexOf() might be the best choice

Author: Wu Chia Chong

My main areas of interest are software architectures and software design methods, patterns, and new trends in software development.

Author: Wu Chia Chong

My main areas of interest are software architectures and software design methods, patterns, and new trends in software development.