Check if String Doesn't include Substring in JavaScript

avatar

Borislav Hadzhiev

Sun Oct 17 20212 min read

Check if String Doesn't include Substring #

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.

index.js
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.

index.js
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.

By negating the return value from the includes method we get if the value isn't contained in the string.

Here are some more examples of using the logical NOT (!) operator.

index.js
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.

When you negate a falsy value, the operator returns true, in all other cases it returns false.

Falsy values are: null, undefined, empty string, NaN, 0 and false.

The String.includes method is not supported in Internet Explorer. If you have to support the browser, use the indexOf method instead.

Check if String Doesn't include Substring with indexOf #

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.

index.js
// 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.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee