0

Can someone elucidate a method that will swap all vowel occurrences in a string with the char 'i'.

For a user input of "Hello world!", "Hilli wirld!" should be returned.

Method below can only remove vowels, rather than replacing them with a chosen char. I do not want to use string replace. I must take a more laborious route of manipulating the array.

function withoutVowels(string) {

  var withoutVowels = "";
  for (var i = 0; i < string.length; i++) {
      if (!isVowel(string[i])) {
        withoutVowels += string[i];
      }
    }
    return withoutVowels;
}

function isVowel(char) {
  return 'aeiou'.includes(char);
}

console.log(withoutVowels('Hello World!'));
hola wrld
  • 3
  • 3
  • 3
    Does this answer your question? [Fastest method to replace all instances of a character in a string](https://stackoverflow.com/questions/2116558/fastest-method-to-replace-all-instances-of-a-character-in-a-string) – Eric Feb 15 '20 at 15:34
  • It seems you're looking for a replacement for English vowels, not vowels ! – Alice Oualouest Feb 15 '20 at 15:45

2 Answers2

3

Without using string replace, but with RegExp :)

function withoutVowels(string, replaceWith) {
  return string.split(/[aeiou]/).join(replaceWith)
}

console.log(withoutVowels('Hello World!', 'i'));
Max
  • 1,996
  • 1
  • 10
  • 16
0

You can simply add an else statement to your existing logic. Better rename the function too.

function replaceVowels(string) {

  var withoutVowels = "";
  const replacement = "i";
  for (var i = 0; i < string.length; i++) {
      if (!isVowel(string[i])) {
        withoutVowels += string[i];
      } else {
        withoutVowels += replacement;
      }
    }
    return withoutVowels;
}

function isVowel(char) {
  return 'aeiou'.includes(char);
}

console.log(replaceVowels('Hello World!'));
igg
  • 2,172
  • 3
  • 10
  • 33