How do I check if string contains substring? [duplicate]
Solution 1:
Like this:
if (str.indexOf("Yes") >= 0)
...or you can use the tilde operator:
if (~str.indexOf("Yes"))
This works because indexOf()
returns -1
if the string wasn't found at all.
Note that this is case-sensitive.
If you want a case-insensitive search, you can write
if (str.toLowerCase().indexOf("yes") >= 0)
Or:
if (/yes/i.test(str))
The latter is a regular expression or regex.
Regex breakdown:
-
/
indicates this is a regex -
yes
means that the regex will find those exact characters in that exact order -
/
ends the regex -
i
sets the regex as case-insensitive -
.test(str)
determines if the regular expression matchesstr
To sum it up, it means it will see if it can find the lettersy
,e
, ands
in that exact order, case-insensitively, in the variablestr
Solution 2:
You could use search or match for this.
str.search( 'Yes' )
will return the position of the match, or -1 if it isn't found.
Solution 3:
It's pretty late to write this answer, but I thought of including it anyhow. String.prototype
now has a method includes
which can check for substring. This method is case sensitive.
var str = 'It was a good date';
console.log(str.includes('good')); // shows true
console.log(str.includes('Good')); // shows false
To check for a substring, the following approach can be taken:
if (mainString.toLowerCase().includes(substringToCheck.toLowerCase())) {
// mainString contains substringToCheck
}
Check out the documentation to know more.
Solution 4:
Another way:
var testStr = "This is a test";
if(testStr.contains("test")){
alert("String Found");
}
** Tested on Firefox, Safari 6 and Chrome 36 **