How can I correctly check if a string does NOT contain a specific word?

前端 未结 6 1192
一个人的身影
一个人的身影 2021-01-11 15:01

I am currently trying to figure out how to solve the above named problem. Specifically I want to check if the string does not contain the word \"stream\" both in ca

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-11 15:29

    You may want to compare the returned results of your include() with strictly equal operands, === false or === true, it's much better practice however not really needed for this, just looks like you might benefit from knowing the different as comparing boolean to a string is an odd thing to do. I'd also not be checking "Stream" and "stream" try using toLowerCase() instead like so, var str1_check = gewaesser_name1.toLowerCase();

    I'd check for stream using the lowercase "stream" as your new strings will all be in lower case, as well you want them to be separate from your initial variables as you may not want those names forced to lowercase. I'd use str1_check.includes("stream") to check if this string has the string "stream" in it, because this result is truthy or falsey you can perform your check like so.

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

    I looks like your if logic here was if the first name doesn't contain "stream" or name 1 and 2 do not contain stream but your checking name 1 with lowercase "stream" and name 2 with uppercase "stream". it looks like you just want both names not to contain stream, this can be much more easily performed like this.

    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
    }
    

提交回复
热议问题