Last updated: Aug 31, 2022
Photo from Unsplash
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 forward slashes
/ / mark the beginning and end of the regular expression.
is called a character class and 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 occurrence.
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.
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.