Borislav Hadzhiev
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 - /[aeiou]/gi
, e.g.
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.For example, [abc]
matches the characters a
, b
and c
.
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.
The i
flag is used to make the search case insensitive. These two regular
expressions are the same:
/[aeiou]/gi
/[aeiouAEIOU]/g
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.
replace()
method does not change the original string, it returns a new string. Strings are immutable in JavaScript.