检查一个必须包含另一个字符串的字符串

时间:2011-05-19 03:54:14

标签: javascript string

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

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

输出为yes,它不是我预期的输出,因为字符串b(wold)不完全包含在字符串a(helloworld)--- wold v.s.世界

有任何检查字符串的建议吗?

6 个答案:

答案 0 :(得分:7)

阅读文档:MDC String.indexOf:)

indexOf返回找到匹配项的索引。这可能是0(表示“在字符串的开头找到”),0是falsy value

如果未找到针,则

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

快乐的编码。

答案 1 :(得分:1)

您需要使用if(a.indexOf(b) > -1)代替。 <{1}}在无法找到字符串时返回indexOf

答案 2 :(得分:1)

如果未找到匹配项,则

.indexOf会返回-1,这是 truthy 值。您需要更明确地检查:

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

答案 3 :(得分:1)

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

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

答案 4 :(得分:0)

那是因为indexOf如果找不到值则返回-1:

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

答案 5 :(得分:0)

您可能想要使用此

if(a.indexOf(b) != -1)
相关问题