Aryan PrajapatKnowledge Contributor
How do you check whether a string contains a substring
How do you check whether a string contains a substring
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Questions | Answers | Discussions | Knowledge sharing | Communities & more.
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
var mainString = “hello”,
subString = “hell”;
mainString.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.
var mainString = “hello”,
subString = “hell”;
mainString.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
var mainString = “hello”,
regex = /hell/;
regex.test(mainString);