1

I am attempting to write a function that will replace all of the vowels in a string with another arbitrary vowel which is selected by an end user. So far, I have been able to write a function that will replace all of the vowels regardless of case, but I would like to be able to preserve the case during replace().

Here is an example of what I am doing right now.


var selectedVowel = "a";
var vowels = /[aeiouAEIOU]/gi;

function rep(string){
let newString = string.replace(vowels, selectedVowel);
return newString;
}

rep("FooBar Exe. unIt");
// returns "FaaBar axe. anat"
// Intended output should return "FaaBar Axe. anAt"

I have tried using Regular Expressions to modify the search criteria for replace() and selectedVowel, but I can't figure out how to use the right regex characters to achieve that end.

I have also looked into methods that use split() to replace the first letter of a word, but this method seems to be limited to the string's indexes, which are not known at the time of the function call.

Any suggestions?

1 Answers1

3

String.prototype.replace() takes a function in place of the substitution string, which is called for each match.

You could write a function that checks each match and replaces it with selectedVowel as-is or uppercased, depending on the case of the matched string.

A little trick to check if a character is upper/lowercase is to compare it to the upper/lowercased version of itself, as in match === match.toUpperCase().

var selectedVowel = "a";
var vowels = /[aeiouAEIOU]/gi;

function rep(string){
  return string.replace(vowels, match => {
    if (match === match.toUpperCase()) {
      return selectedVowel.toUpperCase()
    }
    return selectedVowel
  });
}

console.log(rep("FooBar Exe. unIt")) //=> "FaaBar Axa. anAt"
sdgluck
  • 24,894
  • 8
  • 75
  • 90