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"
Top comments (0)