Mon Nov 08 2021·2 min read
Photo by Patrick Hendry
To remove the vowels from a string, call the
replace() method with the
following regular expression -
str.replace(/[aeiou]/gi, ''). The
replace() method will return a new string
where any vowel in the original string is replaced with an empty string.
const str = 'hello world'; const noVowels = str.replace(/[aeiou]/gi, ''); console.log(noVowels); // 👉️ hll wrld
We passed the following 2 parameters to the String.replace method:
The forwards slashes
/ / mark the beginning and end of the regular expression.
is called a character class and it matches any of the characters in the brackets, in our case - any vowel.
[abc] matches the characters
We used the
g (global) flag because we want to match all occurrences of a
vowel in the string and not just the first one.
i flag is used to make the search case insensitive. These two regular
expressions are the same:
If you need a regex cheatsheet, check out this one from MDN. It's by far the best one out there.
The second parameter we passed to the
replace() method is the replacement
string for each match. Because we want to remove each vowel, we replace it with
an empty string.