Remove the Vowels from a String in JavaScript


Borislav Hadzhiev

Last updated: Aug 31, 2022


Photo from Unsplash

Remove the Vowels from a String #

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:

  1. a regular expression to match in the string
  2. the replacement for each match

The forward slashes / / mark the beginning and end of the regular expression.

The part in the square brackets [] is called a character class and 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 occurrence.

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.

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.

Note that the replace() method doesn't change the original string, it returns a new string. Strings are immutable in JavaScript.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.