Javascript 如果句子包含字符串

Javascript 如果句子包含字符串,javascript,jquery,Javascript,Jquery,如果一个句子包含“helloworld”(没有引号),那么我需要返回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') ){ al

如果一个句子包含“helloworld”(没有引号),那么我需要返回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');
}

我知道。contains不起作用,所以我正在寻找一些起作用的东西。Regex是这里的敌人。

您正在寻找的方法是
indexOf
()。试试下面的方法

if (sentence.indexOf('Hello World') >= 0) { 
  alert('Yes');
} else { 
  alert('No');
}
请尝试以下方法:

if (sentence.indexOf("Hello World") != -1)
{
    alert("Yes");
}
else
{
    alert("No");
}

不要只是尝试。去做吧@斯蒂芬,有没有额外的语义false添加到这里,还是只是为了可读性?呃,对不起。我刚刚删除了评论的那部分,贾里德。事实上,如果字符串不存在,
indexOf
返回
-1
而不是
false
@Stephen,这是我的理解,我想知道如何
!==false
将在这种情况下工作(对javascript来说还是相当新的)。@Stephen,不用担心。这实际上促使我进一步阅读javascript中的严格等式和非严格等式,我学到了不少东西。因此,总体而言,这是一场胜利:)