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.

Example1:

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

Example2:
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 a skilled programmer specializing in Vue.js/Nuxt.js for front-end development and PHP Laravel for back-end solutions. I have a strong focus on API design and development, complemented by experience in web server setup and maintenance. My versatile expertise ensures seamless creation and maintenance of web applications, covering everything from intuitive user interfaces to robust server-side functionality. Passionate about coding and driven by a lifelong learning mindset, I invite you to explore more at danyal.dk.