Borislav Hadzhiev
Sun Oct 17 2021·2 min read
Photo by Nadine Rupprecht
To check if a string doesn't include a substring, use the logical NOT (!)
operator to negate the call to the includes()
method. The NOT (!) operator
returns false
when called on a true
value and vice versa.
const str = 'hello world'; if (!str.includes('bye')) { console.log('✅ string does not include substring'); } else { console.log('⛔️ string includes substring'); }
We used the logical NOT (!) operator to negate the call to the String.includes method.
In the example, we check if the value bye
is contained in the string
hello world
.
const str = 'hello world'; console.log(str.includes('bye')); // 👉️ false console.log(!str.includes('bye')); // 👉️ true
If we use the includes
method without the logical NOT (!) operator, it returns
true
if the value is contained in the string and false
otherwise.
includes
method we get if the value isn't contained in the string.Here are some more examples of using the logical NOT (!) operator.
console.log(!true); // 👉️ false console.log(!false); // 👉️ true console.log(!'hello'); // 👉️ false console.log(!''); // 👉️ true console.log(!null); // 👉️ true
You can imagine that the logical NOT (!) operator first converts the value to a
boolean
and then flips the value.
true
, in all other cases it returns false
.Falsy values are: null
, undefined
, empty string, NaN
, 0
and false
.
String.includes
method is not supported in Internet Explorer. If you have to support the browser, use the indexOf
method instead.To check if a string doesn't include a substring, call to the indexOf()
method on the string, passing it the substring as a parameter. If the indexOf
method returns -1
, then the substring is not contained in the string.
// Supported in IE const str = 'hello world'; if (str.indexOf('bye') === -1) { console.log('✅ string does not include substring'); } else { console.log('⛔️ string includes substring'); }
The
String.indexOf
method returns the index of the first occurrence of a value in a string. If the
value is not contained in the string, the method returns -1
.
If the condition is met and the if
block runs, we can be sure that the
provided value is not contained in the string.