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

niccober picture niccober · Dec 20, 2016 · Viewed 38.6k times · Source

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 capital and lowercase letters.

Here's my code so far:

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

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

None of these variations seem to work for me. Could anyone please give me a hint what's the problem here? I used the indexOf method before many times but always when I wanted to check if a string did contain a specific word, not the other way round.

Answer

Nina Scholz picture Nina Scholz · Dec 20, 2016

I suggest to use String+toLowerCase and check with String#indexOf, because it works in every browser.

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