Checking if a string contains a substring is a common task in JavaScript programming. In this blog, we will explore different ways to accomplish this and find the best approach to use.
The simplest and preferred method is to use the includes()
method on a string. Introduced in ES6/ES2015, this method returns true
if the string contains the specified substring, and false
otherwise.
'a nice string'.includes('nice') // true
Please note that includes()
is supported in all modern browsers except Internet Explorer. For full browser compatibility, you can use a polyfill like Polyfill.io or an alternative polyfill.
The includes()
method also accepts an optional second parameter, an integer that indicates the position to start searching from:
'a nice string'.includes('nice') // true
'a nice string'.includes('nice', 3) // false
'a nice string'.includes('nice', 2) // true
Before ES6, the common method to check for a substring in a string was to use indexOf()
. This string method returns -1 if the substring is not found, and the index of the starting character of the substring if it is found. The second parameter of indexOf()
can also be used to set the starting point for the search:
'a nice string'.indexOf('nice') !== -1 // true
'a nice string'.indexOf('nice', 3) !== -1 // false
'a nice string'.indexOf('nice', 2) !== -1 // true
By using these methods, you can effectively check if a string contains a substring in JavaScript.