繁体   English   中英

使用indexOF()JavaScript测试子字符串

[英]testing a substring with indexOF() javascript

我正在尝试使用indexOf()检查一个子字符串,当要测试的字符串存在时它应该返回true,否则返回false。 由于某种原因,我的代码总是返回true?

为什么此代码不起作用,如何解决?

function checkSpam(str) {

if(str == str.indexOf('yyy') || str.indexOf('xxx')) {
    return true;
}

return false;
}

Javascript的indexOf()返回数字,而不是字符串,请参阅: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

您应该是:

if(-1 != str.indexOf('yyy') || -1 != str.indexOf('xxx')) {
 return true;
}

并非总是true

您的条件由两部分组成。 第一部分str == str.indexOf('yyy')始终为false,除非str的值为"-1" 第二部分str.indexOf('xxx')将始终为true,除非字符串以xxx开头,否则indexOf调用的结果将为零。

因此,如果str"-1"或不以xxx开头,则结果为true

如果要检查字符串是否包含xxxyyy ,则应在条件的两个部分中检查indexOf的结果:

if (str.indexOf('yyy') != -1 || str.indexOf('xxx') != -1) {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM