检查字符串是否包含某段文本

2022-08-30 00:38:00

可能的重复项:
检查文本是否在字符串
JavaScript 中:字符串包含

我正在尝试检查导入到应用程序中的字符串是否包含某段文本。我知道如何使用jQuery做到这一点,但是我如何使用直接的JavaScript做到这一点?


答案 1

你来了: ES5

var test = 'Hello World';
if( test.indexOf('World') >= 0){
  // Found world
}

使用ES6,最好的方法是使用函数来测试字符串是否包含外观工作。includes

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

答案 2