如何检查字符串是否包含子字符串? [英] How do I check if string contains substring?
问题描述
我有一个购物车,在下拉菜单中显示产品选项,如果他们选择是,我想让页面上的其他字段可见。
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 (+ $6.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.
推荐答案
像这样:
if (str.indexOf("Yes") >= 0)
...或者您可以使用代字号运算符:
...or you can use the tilde operator:
if (~str.indexOf("Yes"))
这是有效的,因为 indexOf()
返回 -1
如果根本找不到字符串。
This works because indexOf()
returns -1
if the string wasn't found at all.
请注意,这是区分大小写的。
如果你想要一个不区分大小写的搜索,你可以写
Note that this is case-sensitive.
If you want a case-insensitive search, you can write
if (str.toLowerCase().indexOf("yes") >= 0)
或者,
if (/yes/i.test(str))
这篇关于如何检查字符串是否包含子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!