To remove vowels from a string, call the replace()
method and pass the regular expression, /[aeiou]/gi
, and an empty string to the replace()
method.
let str = "Learning JavaScript"; let noVowelsStr = str.replace(/[aeiou]/gi, ''); console.log(noVowelsStr); //"Lrnng JvScrpt"
The replace() method will not update the original string; instead, it will return a new string in which all the vowels are replaced with an empty string.
The replace()
method accepts two arguments:
The regular expression is created using forward slashes. For example, /\d/
is a regular expression and it matches any digit from 0 to 9.
In a regular expression, anything that you write in the square brackets is called a character class, and it matches any character contained in the brackets. For example, [xyz]
matches x, y and z.
The "g
" flag matches all occurrences of a vowel. Without the g
flag, the replace()
method will only replace the first occurrence of a vowel.
let str = "Learning JavaScript"; let noVowelsStr = str.replace(/[aeiou]/i, ''); console.log(noVowelsStr); //"Larning JavaScript"
The "i
" flag performs a case-insensitive match. If you don't specify the "i
" flag, you have to write the regular expression like this /[aeiouAEIOU]/g
.