Javascript 检查字符串是否有某段文本

Javascript 检查字符串是否有某段文本,javascript,string,Javascript,String,可能的重复项: 我试图检查我导入应用程序的字符串是否有特定的文本。我知道如何使用jQuery实现这一点,但如何使用直接JavaScript实现这一点呢?给你:ES5 var test = 'Hello World'; if( test.indexOf('World') >= 0){ // Found world } 使用ES6最好的方法是使用includes函数来测试字符串是否包含查找工作 const test = 'Hello World'; if (test.includes

可能的重复项:


我试图检查我导入应用程序的字符串是否有特定的文本。我知道如何使用jQuery实现这一点,但如何使用直接JavaScript实现这一点呢?

给你:ES5

var test = 'Hello World';
if( test.indexOf('World') >= 0){
  // Found world
}
使用ES6最好的方法是使用
includes
函数来测试字符串是否包含查找工作

const test = 'Hello World';
if (test.includes('World')) { 
  // Found world
}

如果字符串以“World”开头呢?运算符应该是
>=0
。如果我理解正确,并且>=0值是匹配的-1 betterI喜欢
if(~test.indexOf('World'))
betterWhen使用ES6?这里复制一个基准,用于检查字符串是否在字符串中的最常见方法: