Advertisement
728x90
There are 3 possible ways to check whether a string contains a substring or not,
1. Using includes: ES6 provided String.prototype.includes method to test a string contains a substring
javascript
1var mainString = "hello",
2 subString = "hell";
3
4mainString.includes(subString);2. Using indexOf: In an ES5 or older environment, you can use String.prototype.indexOf which returns the index of a substring. If the index value is not equal to -1 then it means the substring exists in the main string.
javascript
1var mainString = "hello",
2 subString = "hell";
3
4mainString.indexOf(subString) !== -1;3. Using RegEx: The advanced solution is using Regular expression's test method(RegExp.test), which allows for testing for against regular expressions
javascript
1var mainString = "hello",
2 regex = /hell/;
3
4regex.test(mainString);Advertisement
Responsive Ad
🎯 Practice NowRelated Challenge
JavaScript Coding Exercise 37
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement
728x90
121of476