The vowel case

Solving code wars kata problem: replacing vowels with numbers.

In this problem, we are required to replace vowels in a given string with some numbers and reverse it if required. Here is the problem:

Step 1: Create a function called encode() to replace all the lowercase vowels in a given string with numbers according to the following pattern:

a -> 1
e -> 2
i -> 3
o -> 4
u -> 5

For example, encode("hello") would return "h2ll4". There is no need to worry about uppercase vowels in this kata.

Step 2: Now create a function called decode() to turn the numbers back into vowels according to the same pattern shown above.

For example, decode("h3 th2r2") would return "hi there".

Here is the simplest solution I could come up with:

First, I started with the encode and used the replaceAll() to replace all the vowels in the provided string.

function encode(string) {
  string = string.replaceAll(/a/gi,"1");
  string = string.replaceAll(/e/gi,"2");
  string = string.replaceAll(/i/gi,"3");
  string = string.replaceAll(/o/gi,"4");
  string = string.replaceAll(/u/gi,"5");
  return string;
}

The g modifier after each of the vowels is a regular expression global match and it allows the function to replace all occurrences of the specified vowel with the intended number instead of stopping at the first match.

The i modifier specifies a case-insensitive match.

The decode function is just a reversal of the encode function: just replace the numbers with the letters and vice versa.

function decode(string) {
  string = string.replaceAll(/1/gi,"a");
  string = string.replaceAll(/2/gi,"e");
  string = string.replaceAll(/3/gi,"i");
  string = string.replaceAll(/4/gi,"o");
  string = string.replaceAll(/5/gi,"u");
  return string
}

That is pretty much it.

Combined:

function encode(string) {
  string = string.replaceAll(/a/gi,"1");
  string = string.replaceAll(/e/gi,"2");
  string = string.replaceAll(/i/gi,"3");
  string = string.replaceAll(/o/gi,"4");
  string = string.replaceAll(/u/gi,"5");
  return string;
}

function decode(string) {
  string = string.replaceAll(/1/gi,"a");
  string = string.replaceAll(/2/gi,"e");
  string = string.replaceAll(/3/gi,"i");
  string = string.replaceAll(/4/gi,"o");
  string = string.replaceAll(/5/gi,"u");
  return string
}

I also found multiple solutions for the problem from other people and there somewhat slightly complicated.

Here is a link to the compilation of the other solutions.