DEV Community

Cover image for reverse only the alphabetical ones
chandra penugonda
chandra penugonda

Posted on

reverse only the alphabetical ones

You are given a string that contains alphabetical characters (a - z, A - Z) and some other characters ($, !, etc.). For example, one input may be:

input: 'sea!$hells3'
Enter fullscreen mode Exit fullscreen mode

Can you reverse only the alphabetical ones?

reverseOnlyAlphabetical('sea!$hells3')
Enter fullscreen mode Exit fullscreen mode
output: 'sll!$ehaes3'
Enter fullscreen mode Exit fullscreen mode

Solution

function reverse(str) {
  const alphas = [];
  for (let i = 0; i < str.length; i++) {
    if (/[a-z]/gi.test(str[i])) {
      alphas.push(str[i]);
    }
  }
  let output = "";
  for (const char of str) {
    if (/[a-z]/gi.test(char)) {
      output += alphas.pop();
    } else {
      output += char;
    }
  }
  return output;
}

console.log(reverse("sea!$hells3")); // "sll!$ehaes3"

Enter fullscreen mode Exit fullscreen mode

Top comments (0)