Javascript 检查文本是否在字符串中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6614424/
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
Check if text is in a string
提问by user710502
I want to check is some text is in a string for instance i have a string
我想检查一些文本是否在字符串中,例如我有一个字符串
str = "car, bycicle, bus"
and I have another string
我还有另一个字符串
str2 = "car"
I want to check if str2 is in str.
我想检查 str2 是否在 str 中。
I am a newbie in javascript so please bear with me :)
我是 javascript 的新手,所以请多多包涵:)
Regards
问候
回答by Vivin Paliath
if(str.indexOf(str2) >= 0) {
...
}
Or if you want to go the regex route:
或者,如果您想走正则表达式路线:
if(new RegExp(str2).test(str)) {
...
}
However you may face issues with escaping (metacharacters) in the latter, so the first route is easier.
但是,在后者中您可能会遇到转义(元字符)的问题,因此第一种方法更容易。
回答by Furkan Durmaz
ES5
ES5
if(str.indexOf(str2) >= 0) {
...
}
ES6
ES6
if (str.includes(str2)) {
}
回答by Doug Chamberlain
str.lastIndexOf(str2) > 0; this should work. untested though.
str.lastIndexOf(str2) > 0; 这应该有效。虽然未经测试。
回答by darshankhamar
Please use this :
请使用这个:
var s = "foo";
alert(s.indexOf("oo") > -1);