Javascript 如何检查字符串是否包含子字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3480771/
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
How do I check if string contains substring?
提问by Jordan Garis
I have a shopping cart that displays product options in a dropdown menu and if they select "yes", I want to make some other fields on the page visible.
我有一个在下拉菜单中显示产品选项的购物车,如果他们选择“是”,我想让页面上的其他一些字段可见。
The problem is that the shopping cart also includes the price modifier in the text, which can be different for each product. The following code works:
问题是购物车还包含文本中的价格修饰符,每个产品的价格修饰符可能不同。以下代码有效:
$(document).ready(function() {
$('select[id="Engraving"]').change(function() {
var str = $('select[id="Engraving"] option:selected').text();
if (str == "Yes (+ .95)") {
$('.engraving').show();
} else {
$('.engraving').hide();
}
});
});
However I would rather use something like this, which doesn't work:
但是我宁愿使用这样的东西,它不起作用:
$(document).ready(function() {
$('select[id="Engraving"]').change(function() {
var str = $('select[id="Engraving"] option:selected').text();
if (str *= "Yes") {
$('.engraving').show();
} else {
$('.engraving').hide();
}
});
});
I only want to perform the action if the selected option contains the word "Yes", and would ignore the price modifier.
如果所选选项包含“是”一词,我只想执行该操作,并且会忽略价格修饰符。
回答by SLaks
Like this:
像这样:
if (str.indexOf("Yes") >= 0)
...or you can use the tilde operator:
...或者您可以使用波浪号运算符:
if (~str.indexOf("Yes"))
This works because indexOf()returns -1if the string wasn't found at all.
这是有效的,因为如果根本找不到字符串,则indexOf()返回-1。
Note that this is case-sensitive.
If you want a case-insensitive search, you can write
请注意,这是区分大小写的。
如果你想要一个不区分大小写的搜索,你可以写
if (str.toLowerCase().indexOf("yes") >= 0)
Or:
或者:
if (/yes/i.test(str))
回答by hookedonwinter
回答by Munim Dibosh
It's pretty late to write this answer, but I thought of including it anyhow. String.prototypenow has a method includeswhich can check for substring. This method is case sensitive.
写这个答案已经很晚了,但我想无论如何都要包括它。String.prototype现在有一个includes可以检查子字符串的方法。此方法区分大小写。
var str = 'It was a good date';
console.log(str.includes('good')); // shows true
console.log(str.includes('Good')); // shows false
To check for a substring, the following approach can be taken:
要检查子字符串,可以采用以下方法:
if (mainString.toLowerCase().includes(substringToCheck.toLowerCase())) {
// mainString contains substringToCheck
}
Check out the documentationto know more.
查看文档以了解更多信息。
回答by Andy Braham
Another way:
其它的办法:
var testStr = "This is a test";
if(testStr.contains("test")){
alert("String Found");
}
** Tested on Firefox, Safari 6 and Chrome 36 **
** 在 Firefox、Safari 6 和 Chrome 36 上测试**
回答by Oriol
ECMAScript 6 introduces String.prototype.includes, previously named contains.
ECMAScript 6 引入了String.prototype.includes,之前命名为contains.
It can be used like this:
它可以像这样使用:
'foobar'.includes('foo'); // true
'foobar'.includes('baz'); // false
It also accepts an optional second argument which specifies the position at which to begin searching:
它还接受一个可选的第二个参数,该参数指定开始搜索的位置:
'foobar'.includes('foo', 1); // false
'foobar'.includes('bar', 1); // true
It can be polyfilledto make it work on old browsers.
它可以被polyfill以使其在旧浏览器上工作。
回答by robkorv
You can use this Polyfill in ie and chrome
你可以在 ie 和 chrome 中使用这个 Polyfill
if (!('contains' in String.prototype)) {
String.prototype.contains = function (str, startIndex) {
"use strict";
return -1 !== String.prototype.indexOf.call(this, str, startIndex);
};
}
回答by Kareem
Returns number of times the keyword is included in the string.
返回关键字包含在字符串中的次数。
var count = "I have one keyword".match(/keyword/g);
var clean_count = !count ? false : count.length;
回答by Parth Raval
The includes() method determines whether one string may be found within another string, returning true or false as appropriate.
Syntax :-string.includes(searchString[, position])
searchString:-A string to be searched for within this string.
position:-Optional. The position in this string at which to begin searching for searchString; defaults to 0.
include() 方法确定是否可以在另一个字符串中找到一个字符串,并根据需要返回 true 或 false。
语法:-string.includes(searchString[, position])
searchString:-要在此字符串中搜索的字符串。
位置:-可选。在此字符串中开始搜索 searchString 的位置;默认为 0。
string = 'LOL';
console.log(string.includes('lol')); // returns false
console.log(string.includes('LOL')); // returns true
回答by Sherali Turdiyev
I know that best way is str.indexOf(s) !== -1;http://hayageek.com/javascript-string-contains/
我知道最好的方法是str.indexOf(s) !== -1;http://hayageek.com/javascript-string-contains/
I suggest another way(str.replace(s1, "") !== str):
我建议另一种方式(str.replace(s1, "") !== str):
var str = "Hello World!", s1 = "ello", s2 = "elloo";
alert(str.replace(s1, "") !== str);
alert(str.replace(s2, "") !== str);
回答by Selfish
If you are capable of using libraries, you may find that Lo-DashJS library is quite useful. In this case, go ahead and check _.contains()(replaced by _.includes()as of v4).
如果您能够使用库,您可能会发现Lo-DashJS 库非常有用。在这种情况下,继续检查_.contains()(_.includes()从 v4 开始替换)。
(Note Lo-Dash convention is naming the library object _. Don't forget to check installation in the same page to set it up for your project.)
(注意 Lo-Dash 约定将库对象命名为 _。不要忘记在同一页面中检查安装以针对您的项目进行设置。)
_.contains("foo", "oo"); // → true
_.contains("foo", "bar"); // → false
// Equivalent with:
_("foo").contains("oo"); // → true
_("foo").contains("bar"); // → false
In your case, go ahead and use:
在您的情况下,请继续使用:
_.contains(str, "Yes");
// or:
_(str).contains("Yes");
..whichever one you like better.
..你更喜欢哪一个。

