javascript regex not in a set of characters

How to use JavaScript regex to exclude a set of characters?

JavaScript regex is a powerful tool to match patterns in a string. Sometimes we may want to match everything except a certain set of characters. In this case, we can use the caret (^) symbol inside square brackets to negate the set of characters.

Example:

Suppose we want to match all characters except the vowels (a, e, i, o, u):


const str = "hello world";
const regex = /[^aeiou]/g;
const result = str.match(regex);
console.log(result); // ['h', 'l', 'l', ' ', 'w', 'r', 'l', 'd']

In the above example, we create a regex that matches any character that is not a vowel using the [^aeiou] pattern. The g flag indicates that we want to search for all matches in the string. We then use the match() method on the string "hello world" to find all matches of the regex pattern and store the results in the result variable.

The result variable contains an array of all the characters in the string that are not vowels.

Alternative method:

We can also use the negative lookahead assertion (?!pattern) to exclude a set of characters.

Example:


const str = "hello world";
const regex = /.(?!aeiou)/g;
const result = str.match(regex);
console.log(result); // ['h', 'l', 'l', ' ', 'w', 'r', 'l', 'd']

In the above example, we create a regex that matches any character except when followed by a vowel using the .(?!aeiou) pattern. The g flag indicates that we want to search for all matches in the string. We then use the match() method on the string "hello world" to find all matches of the regex pattern and store the results in the result variable.

The result variable contains an array of all the characters in the string that are not followed by a vowel.

Using negation in regex can be a bit tricky at first, but it can be very useful in certain situations. Experiment with different patterns and see what works best for your use case!

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe