ℙℕℤℝ 2010-08-13 21:25
浏览 421
已采纳

如何检查字符串是否包含子字符串? [重复]

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.

</div>

转载于:https://stackoverflow.com/questions/3480771/how-do-i-check-if-string-contains-substring

  • 写回答

13条回答 默认 最新

  • 旧行李 2010-08-13 21:28
    关注

    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.

    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))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(12条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料