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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay