-5

How can I replace all the vowels in uppercase, with less code?

var str = "aaeeiioouu";
str=str.replace(/a/g, "A");
str=str.replace(/e/g, "E");
str=str.replace(/i/g, "I");
str=str.replace(/o/g, "O");
str=str.replace(/u/g, "U");
document.write(str);
Ryszard Czech
  • 18,032
  • 4
  • 24
  • 37
Sk1Ye
  • 11
  • 2

2 Answers2

6

replace accepts the function as the second parameter, you can use that and return the uppercase result. Also you can modify your regex to accept all vowels. You can use /[aeiou]/g

var str = "aaeeiioouu";
str=str.replace(/[aeiou]/g, (c) => {
   return c.toUpperCase();
});
console.log(str);

According to the replace docs:

You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. (Note: the above-mentioned special replacement patterns do not apply in this case.) Note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.

The arguments to the function are as follows:

Possible name : Supplied value

match : The matched substring. (Corresponds to $& above.)

p1, p2, ... : The nth parenthesized submatch string, provided the first argument to replace() was a RegExp object. (Corresponds to $1, $2, etc. above.) For example, if /(\a+)(\b+)/, was given, p1 is the match for \a+, and p2 for \b+.

offset : The offset of the matched substring within the whole string being examined. (For example, if the whole string was 'abcd', and the matched substring was 'bc', then this argument will be 1.)

string : The whole string being examined.

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
0

While not nearly as efficient as the regex .replace() solution above, here's an alternative that iterates through each letter and capitalizes vowels.

var str = "aaeeiioouuxyz";
    str = str.split('');
for (var i = 0; i < str.length; i++)
  if ("aeiou".indexOf(str[i]) > -1) str[i] = str[i].toUpperCase();

console.log(str.join(''));
Epoch
  • 656
  • 4
  • 16