JavaScript: string contains substring
The simplest way is with the includes
method.
'some big string'.includes('big'); // returns true
'some big string'.includes('Big'); // returns false
The includes
method is only available on browser that support ES6. To work with older browsers, you can use indexOf
. If it cannot find the substring, it returns -1
:
'some big string'.indexOf('big') !== -1; // returns true
'some big string'.indexOf('Big') !== -1; // returns false
Notice you can also use indexOf to get the index of the first substring found.
'some big string'.indexOf('s'); // returns 0
```
Questions
What's the output?
'abc'.includes('b');
What's the output?
'a b c'.includes('a c');
What's the output?
'a b c'.indexOf('a c');
What's the output?
'abc'.indexOf('b');