hola wrld
hola wrld

Reputation: 3

How to replace all vowels in a string with a char?

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!'));

Upvotes: 0

Views: 1002

Answers (2)

Max
Max

Reputation: 2036

Without using string replace, but with RegExp

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

console.log(withoutVowels('Hello World!', 'i'));

Upvotes: 3

igg
igg

Reputation: 2250

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!'));

Upvotes: 0

Related Questions