How to check if string contains a substring in JavaScript?
The ability to check a string contains a substring should have been standard in JavaScript. Prior to ES6, there were no standard functions to do this check.
The modern JavaScript ECMAScript 6 introduces String#includes for checking that. In this article, we tried to compile most of the ways to check a substring exists inside a string.
Using String#includes:
ECMAScript 6 introduces String#includes, it checks a substring is included inside a string or not. It is widely supported by all browsers except IE:
// Approach #1: const str = 'World Health Organization'; console.log(str.includes('Health')); // true
Using String#indexOf:
String#indexOf is quite an old string method that we can use to checks a substring is included inside a string or not. It is widely supported by all browsers except IE8:
// Approach #2: const str = 'World Health Organization'; console.log(str.indexOf('Health') > -1); // true
Using test method:
test() can be used to checks a substring is included inside a string or not.
// Approach #3: const str = 'World Health Organization'; console.log(/Health/i.test(str)); // true
Using String#search:
String#search can be used to checks a substring is included inside a string or not. It is widely supported by all browsers:
// Approach #4: const str = 'World Health Organization'; console.log(str.search('Health') > -1); // true
Using String#match:
String#match can be used to checks a substring is included inside a string or not. It is widely supported by all browsers:
// Approach #5: const str = 'World Health Organization'; console.log(str.match('Health') !== null); // true