How do I check if string contains substring?
This question already has an answer here:
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))
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.
Another way:
var testStr = "This is a test";
if(testStr.contains("test")){
alert("String Found");
}
** Tested on Firefox, Safari 6 and Chrome 36 **
链接地址: http://www.djcxy.com/p/2038.html上一篇: 检查一个字符串是否有一段文字
下一篇: 如何检查字符串是否包含子字符串?