reverse only the alphabetical ones
chandra penugonda
Posted on August 11, 2023
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'
Can you reverse only the alphabetical ones?
reverseOnlyAlphabetical('sea!$hells3')
output: 'sll!$ehaes3'
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"
💖 💪 🙅 🚩
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.