Skip to content
the poor coder

javascript regex not in a set of characters

Poor Man
Published
Reading time
2 min read
On this page

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):

JavaScript

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:#

JavaScript

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!

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC