reverse only the alphabetical ones

chandrapenugonda

chandra penugonda

Posted on August 11, 2023

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
💖 💪 🙅 🚩
chandrapenugonda
chandra penugonda

Posted on August 11, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related