javascript 如果句子包含字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4248630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
if sentence contains string
提问by wish_i_was_nerdy
If a sentence contains "Hello World" (no quotes) then I need to return true and do something. Possible sentences could be like this:
如果一个句子包含“Hello World”(没有引号),那么我需要返回 true 并做一些事情。可能的句子是这样的:
var sentence = "This is my Hello World and I like widgets."
var sentence = "Hello World - the beginning of all"
var sentence = "Welcome to Hello World"
if ( sentence.contains('Hello World') ){
alert('Yes');
} else {
alert('No');
}
I know the .contains does not work, so I'm looking for something does work. Regex is the enemy here.
我知道 .contains 不起作用,所以我正在寻找一些有用的东西。正则表达式是这里的敌人。
回答by JaredPar
The method you're looking for is indexOf(Documentation). Try the following
您正在寻找的方法是indexOf( Documentation)。尝试以下
if (sentence.indexOf('Hello World') >= 0) {
alert('Yes');
} else {
alert('No');
}
回答by Tim S. Van Haren
Try this instead:
试试这个:
if (sentence.indexOf("Hello World") != -1)
{
alert("Yes");
}
else
{
alert("No");
}

