【问题标题】:Check a string that MUST contain another string [duplicate]检查一个必须包含另一个字符串的字符串[重复]
【发布时间】:2011-08-28 13:19:24
【问题描述】:

我想检查字符串 b 是否完全包含在字符串 a 中。
我试过了:

var a = "helloworld";
var b = "wold";
if(a.indexOf(b)) { 
    document.write('yes'); 
} else { 
    document.write('no'); 
}

输出是肯定的,这不是我的预期输出,因为字符串 b(wold) 没有完全包含在字符串 a(helloworld) --- wold vs.世界

有什么检查字符串的建议吗?

【问题讨论】:

标签: javascript string


【解决方案1】:

阅读文档:MDC String.indexOf :)

indexOf 返回找到匹配项的索引。这可能是 0(这意味着“在字符串的开头找到”)并且 0 是 falsy value

indexOf 将返回 -1 如果没有找到针(并且 -1 是 truthy value)。因此,需要调整测试逻辑以使用这些返回码工作。找到字符串(在开头或其他地方):index >= 0index > -1index != -1;未找到字符串:index < 0index == -1

编码愉快。

【讨论】:

    【解决方案2】:

    您需要改用if(a.indexOf(b) > -1)indexOf 在找不到字符串时返回 -1

    【讨论】:

      【解决方案3】:

      .indexOf 如果没有找到匹配项,则返回-1,这是一个 truthy 值。您需要更明确地检查:

      if (a.indexOf(b) != -1)
      

      【讨论】:

        【解决方案4】:

        这是因为如果没有找到值,indexOf 返回 -1:

        if(a.indexOf(b) != -1) {
        

        【讨论】:

          【解决方案5】:

          你可能想用这个

          if(a.indexOf(b) != -1)
          

          【讨论】:

            【解决方案6】:

            您需要测试结果是否为-1。 -1 表示不匹配,但在布尔意义上计算为真。

            var a = "helloworld";
            var b = "wold";
            if(a.indexOf(b) > -1) { 
              document.write('yes'); 
            } else { 
              document.write('no'); 
            }
            

            【讨论】:

              猜你喜欢
              • 2011-08-31
              • 2013-03-13
              • 1970-01-01
              • 2012-12-06
              • 1970-01-01
              • 2021-05-06
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多