Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

javascript - 如何检查字符串是否包含子字符串? [重复](How do I check if string contains substring? [duplicate])

This question already has an answer here:(这个问题在这里已有答案:)

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.(如果所选选项包含单词“是”,我只想执行操作,并忽略价格修饰符。)

  ask by Jordan Garis translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Like this:(像这样:)

if (str.indexOf("Yes") >= 0)

...or you can use the tilde operator:(...或者你可以使用代字号运算符:)

if (~str.indexOf("Yes"))

This works because indexOf() returns -1 if 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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...