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 ๐