Javascript 检查字符串是否有特定的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6629728/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:33:15  来源:igfitidea点击:

Check if a string has a certain piece of text

javascriptstring

提问by swickblade

Possible Duplicates:
Check if text is in a string
JavaScript: string contains

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

I'm trying to check if a string I import into my application has a certain piece of text. I know how to do this with jQuery, but how do I do it with straight up JavaScript?

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

回答by Eddie

Here you go: ES5

给你:ES5

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

With ES6best way would be to use includesfunction to test if the string contains the looking work.

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

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