How to remove vowels from a JS string?

Asked

Viewed 1,814 times

1

I want to create a JS function that removes vowels from a word. I tried with replace, regular expression, but I couldn’t.

2 answers

3


You can use this regex which will remove even accented vowels:

/[aeiouà-ú]/gi

Flags:
g -> global. Busca por todas as ocorrências.
i -> case insensitive. Não faz distinção entre maiúsculas e minúsculas.

Behold:

function removeVogaisString( remove ){
   return remove.replace(/[aeiouà-ú]/gi,'');
}

var resultado = removeVogaisString( "OláÁéôãõ, mundo!" );

console.log( resultado );

  • What is the purpose of /gi existing in replace?

  • g (global): will search for all occurrences. i (case insensitive): does not distinguish between upper and lower case.

1

Functional example with regular expressions:

const example = 'Olá, mundo!';

console.log(example.replace(/(a|e|i|o|u)/gi, ''));

Adding more characters

If you want to add more characters to be removed, just add more next to |u.
For example, if you want to remove the letter z also, simply change the expression of:

/(a|e|i|o|u)/gi

To:

/(a|e|i|o|u|z)/gi
  • Simpler is /[aeiou]/

  • I had tried something more or less like this, but returned Undefined. Function removeVogaisString( remove ){ <br/> remove.replace(/[[ aAeEiIoOuU]]/g,'); } var result = removeVogaisString( "Today it will rain." ); console.log( result );

Browser other questions tagged

You are not signed in. Login or sign up in order to post.