-5

I'm very new to JavaScript and came across an exercise solution that I want to fully understand.

The exercise asked to remove all vowels from a string. The solution:

function disemvowel(str) {
  return str.replace(/[aeiou]/gi, '');
}

I understand the basic syntax:

  • whatever is between the /'s is what you want replaced

  • second parameter is what to replace it with

  • /g is a 'global tag'....? so not just the first instance

My questions:

  • What do the brackets in the solution represent?

  • What is the i after /g? I read that it means ignore, but what is it ignoring?

Thank you for any info!! :)

Ambyjkl
  • 430
  • 4
  • 15
bax
  • 109
  • 6
  • i is for ignoring "case" of string , whether they r uppercase or lowercase – Khan M Feb 16 '18 at 19:35
  • 1
    Read documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions – epascarello Feb 16 '18 at 19:38
  • The `i` is a flag (like the `g`) for `ignorecase`, so the regular expression matches both upper and lower case. The brackets indicate a grouping, matching any character contained within. – Brett DeWoody Feb 16 '18 at 19:40
  • Have you read [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)? – Sebastian Simon Feb 16 '18 at 20:06

4 Answers4

2

What you have there is what's called a "regular expression". In JavaScript, you have what are called "regular expression literals", which is the /[aeiou]/gi thing. The [aeiou] is known as a "character class" or a "character set", which means "match one of aeiou". The g and i after the closing / are flags that determine how the regular expression behaves. g means "global" or "find all matches", and i means "case insensitive". You then replace all these matches with an empty string '' so that all the occurrences of vowels are removed in the generated string

Ambyjkl
  • 430
  • 4
  • 15
  • 1
    Regex101 is a nice site to test these. On the side it shows an explanation. https://regex101.com/r/mw9Gj3/2 – pfg Feb 16 '18 at 19:43
0

You type inside the brackets all characters to match (think of it as a enum of characters). i is for case Insensitive.

Pierre
  • 604
  • 1
  • 7
  • 14
0

/[aeiou]/gi will match a any of the characters a,e,i,o,u with case insensitivity which is what the i at the end is for

Basically in your case it will remove all occurences of vowels from your string (replace vowels with empty string)

const str = "hUnger gamEs";

console.log(str.replace(/[aeiou]/gi, ''));
Shubham Khatri
  • 211,155
  • 45
  • 305
  • 318
0

g modifier: global. All matches (don't return on first match)

i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])