如果句子包含字符串

wis*_*rdy 23 javascript jquery

如果一个句子包含"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');
}
Run Code Online (Sandbox Code Playgroud)

我知道.contains不起作用,所以我正在找一些有用的东西.正则表达式是这里的敌人.

Jar*_*Par 26

您正在寻找的方法是indexOf(文档).请尝试以下方法

if (sentence.indexOf('Hello World') >= 0) { 
  alert('Yes');
} else { 
  alert('No');
}
Run Code Online (Sandbox Code Playgroud)

  • 不要只是尝试。做吧。;) (2认同)

Tim*_*ren 7

试试这个:

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