Home > Back-end >  How the selection of the letter work in function replace /[aeiou/g]?
How the selection of the letter work in function replace /[aeiou/g]?

Time:12-03

I made a code that select vowels and replace them with ""

function disemvowel(str) {
  str = str.replace(/[aeiouAEIOU]/g, "");
  return str;
}

console.log(disemvowel("This website is for losers LOL!"));

But I am not quite sure how this part of the code works = /[aeiouAEIOU]/g why are the vowels inside [] and what the g does? as well as the //

Another question, how could I select both lower and upper case letter at once instead of right [aeiouAEIOU]?

CodePudding user response:

Read this.

/[aeiouAEIOU]/g

is short for

new RegExp( '[aeiouAEIOU]', 'g' )

It constructs a RegExp object which represents a regular expression and some flags. A regular expression defines a set of strings. String.prototype.replace can use this definition to identify the substrings to replace.

The regex pattern

[aeiouAEIOU]

defines the following set of strings: a, e, i, o, u, A, E, I, O, U.

The g flag tells String.prototype.replace to replaces all instances of those substrings (not just the first).

Note that /[aeiou]/ig would be sufficient. The i flag makes operations case-insensitive. (This may have a performance penalty.)

CodePudding user response:

The code inside the replace method is a Regular Expression or Regex.

As described by MDN:

Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec() and test() methods of RegExp, and with the match(), matchAll(), replace(), replaceAll(), search(), and split() methods of String.

If you want to learn more about regex, I recommend taking a look at this website. It helps you to write and visualise the patterns.

  • Related