To remove all vowels from a string in JavaScript, call the replace()
method on the string with this regular expression: /[aeiou]/gi
, i.e., str.replace(/[aeiou]/gi, '')
. replace()
will return a new string where all the vowels in the original string have been replaced with an empty string.
For example:
const str = 'coding beauty';
const noVowels = str.replace(/[aeiou]/gi, '');
console.log(noVowels); // cdng bty
The String replace() Method
The String replace() method takes two arguments:
pattern
– a pattern to search for in the given string. We used a regular expression for this, but it can also be a string.replacement
– the string used to replace the matches of the specified pattern in the string. By passing an empty string (''
), we remove all occurrences of this pattern in the given string.
Note: replace()
does not modify the original string, but returns a new string. Strings are immutable in JavaScript.
Regular Expression Explained
We use the two forward slashes (/ /
) to specify the start and end of the regular expression.
The []
characters are used to specify a pattern that matches any of a specific group of characters. For example, the pattern [abc]
will match 'a'
, 'b'
, or 'c'
. In the same way, the [aeiou]
pattern will match any of the 5 vowel characters in the English alphabet.
The g
(global) regex flag is used to match all occurrences of the regex pattern. Without this flag, only the first pattern match would be removed after calling replace()
.
const str = 'coding beauty';
// "g" regex flag not set
const noVowels = str.replace(/[aeiou]/i, '');
// Only first vowel removed
console.log(noVowels); // cding beauty
The i
(ignore case) flag is used to perform a case-insensitive search for a regex match in the given string. This ensures that all vowels are removed from the string whether they are uppercased or not.
const str = 'cOding bEaUty';
// "i" regex flag NOT set
const noVowels1 = str.replace(/[aeiou]/g, '');
// Only lowercased vowels removed
console.log(noVowels1); // cOdng bEUty
// "i" regex flag set
const noVowels2 = str.replace(/[aeiou]/gi, '');
// All vowels removed
console.log(noVowels2); // cdng bty
For a comprehensive guide to regex patterns in JavaScript, check out this regular expression syntax cheat sheet from the MDN docs.
11 Amazing New JavaScript Features in ES13
This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.