Javascript: How to check if string contain a substring

There are different ways of testing if string contains a substring., let’s take a look at few examples.

Most common and simple method would be following example, this was introduced in ES6/ES2015 and supported in most modern browsers expect IE 6 to 11.


'Hello from the other world'.includes('other') //true

In this example we can see the use of optional second parameter includes accepts.

'Hello from the other world'.includes('other', 2) //false
'Hello from the other world'.includes('other', 4) //true

Before ES6 indexOf() was used instead of includes()
indexOf() was the common method before ES6, that return -1 if string doesn’t contain the substring.

And it returns the index of the substring when it is found, let’s look at examples:

'Hello from the other world'.indexOf('from') !== -1 //true
'Hello from the other world'.indexOf('from', 3) !== -1 //false
'Hello from the other world'.indexOf('from', 2) !== -1 //true

That was quite simple, isn’t it.
See you in next post 🙂

Author: Danyal
I'm skilled programmer with expertise in Vue.js/Nux.js for front-end development and PHP Laravel for back-end development. I excel in building APIs and services, and also have experience in web server setup & maintenance. My versatile skill set allows you to develop and maintain web applications effectively, from the user interface to the server-side functionality. I love coding with never ending learning attitude, thanks for visiting