如何正确检查一个字符串是否不包含特定的单词?

30

我目前正在尝试解决上述问题。具体来说,我想检查字符串是否包含"stream"这个单词,忽略大小写。

这是我的代码:

if (((gewaesser_name1.includes("Stream") == "false") ||
(gewaesser_name1.includes("stream") == "false")) &&
((gewaesser_name2.includes("Stream") == "false") ||
(gewaesser_name2.includes("stream") == "false")))
{var a= "..."}

代码显然无法正常工作,因为结果并不符合我的预期。 在使用以下语法变体之前,我还尝试使用 indexOf 方法:

The code does obviously not work as the results are not what I expect them to be. I also tried to use the indexOf method before using the following syntax variations:

gewaesser_name2.indexOf("stream") == -1
gewaesser_name2.indexOf("stream") < 0

对我来说,这些变化似乎都不起作用。请问有人能给我一个提示,问题出在哪里吗?我以前多次使用过 indexOf 方法,但总是用来检查字符串是否包含特定单词,而不是反过来。


1
在检查之前将大小写规范化。 if (!name.toLowerCase().includes("stream")) {.. - user1106925
你应该使用 &&,而不是 || - Barmar
7个回答

35

我建议使用String+toLowerCaseString#indexOf进行检查,因为它在任何浏览器中都有效。

if (gewaesser_name1.toLowerCase().indexOf("stream") === -1 && gewaesser_name2.toLowerCase().indexOf("stream") === -1) {
    var a = "..."
}

5

indexOf() 是正确的方法,可以通过在测试之前使用 .toLowerCase().toUpperCase() 强制将测试字符串转换为小写或大写来轻松解决大小写问题:

const lookupValue = "stream";
const testString1 = "I might contain the word StReAm and it might be capitalized any way.";
const testString2 = "I might contain the word steam and it might be capitalized any way.";

function testString(testData, lookup){
  return testData.toLowerCase().indexOf(lookup) === -1;
}

function prettyPrint(yesNo){
   return "The string does" + (yesNo ? " NOT" : "") + " contain \"stream\" in some form."
}

console.log(prettyPrint(testString(testString1, lookupValue)));
console.log(prettyPrint(testString(testString2, lookupValue)));


3

您可能希望将include()返回结果与严格相等的操作数 === false 或 === true 进行比较,但这并不是必须的最佳实践。不过,对于将布尔值与字符串进行比较来说,可以说是一件奇怪的事情。我建议使用 toLowerCase() 代替 "Stream" 和 "stream" 的检查,如下所示: var str1_check = gewaesser_name1.toLowerCase();

我建议使用小写字母 "stream" 来检查是否为流,因为您的新字符串都将转换为小写字母,并且您可能不想强制转换这些名称的大小写。我建议使用 str1_check.includes("stream") 检查此字符串中是否含有字符串 "stream",因为这个结果是真假值,您可以像下面这样执行检查。

if(str1_check.includes("stream")) {
//this string contained stream
}

看起来你的if逻辑是如果名字中不包含"stream",或者name1和name2都不包含"stream",但你检查name1时用了小写的"stream",而检查name2时用了大写的"stream"。看起来你只想要两个名字都不包含"stream",这可以更容易地实现如下:

var str1_check = gewaesser_name1.toLowerCase(),
str2_check = gewaesser_name2.toLowrCase();//this way you're not making        multiple toLowerCase calls in your conditional and maintain the state of your two names.

if(!str1_check.includes("stream") && !str2_check.includes("stream")){
//your code on truthey statement
}

1

这是正则表达式中可以执行的操作:

const testString1 = "I might contain the word StReAm and it might be capitalized any way.";
const testString2 = "I might contain the word steam and it might be capitalized any way.";
const re = /stream/i
console.log( !!(testString1.match(re) ));
console.log( !!(testString2.match(re) ))


1
感谢大家快速的反馈,现在代码已经可以完美运行!
我正在使用以下代码:
`if      (gewaesser_name1.toLowerCase().indexOf("stream") === -1 && gewaesser_name2.toLowerCase().indexOf("stream") === -1) 
         {var a = "does NOT contain stream"}

 else    {var a= "does contain stream"}

`


4
如果你已经标记了其他答案作为答案,请不要再发布自己问题的答案。 - Scott Marcus

0

我更喜欢使用像这样的JavaScript RegExp:

function includesMatch(lookupValue, testString){
    var re = new RegExp(lookupValue, 'i'); //Here the 'i' means that we are doing a case insensitive match
    return testString.match(re) !== null
}

var lookup = "stream";
var test1  = "do I have a StrEAm in me?";
var test2  = "well at least I don't";
console.log(includesMatch(lookup, test1));
console.log(includesMatch(lookup, test2));


0

这是一个可以使用字符串作为参数进行检查的一行代码。

const hasForbiddenFruit = diet => ['', '', 'apple'].some(diet.includes.bind(diet.toLowerCase()))
console.log(
   'Adam is good to go:', 
   hasForbiddenFruit(',  also some other aPpLe and so on')
)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接