Reversing all alphabetic characters in JavaScript

We are required to write a JavaScript function that takes in a string and reverses only the alphabetic characters, omitting all non-alphabetic characters from the result.

Problem

Given a string containing both alphabetic and non-alphabetic characters, we need to create a function that filters out non-alphabetic characters and returns the alphabetic characters in reverse order.

Example

Following is the code −

const str = 'exa13mple';
function reverseLetter(str) {
    const res = str.split('')
        .reverse()
        .filter(val => /[a-zA-Z]/.test(val))
        .join('');
    return res;
};
console.log(reverseLetter(str));

Output

elpmaxe

How It Works

The function works by chaining several array methods:

  1. split('') - Converts the string into an array of characters
  2. reverse() - Reverses the order of all characters
  3. filter() - Keeps only alphabetic characters using regex pattern /[a-zA-Z]/
  4. join('') - Combines the filtered characters back into a string

Alternative Approach

Here's another method that filters first, then reverses:

const str = 'hello123world!';
function reverseLettersOnly(str) {
    const alphabetsOnly = str.split('')
        .filter(char => /[a-zA-Z]/.test(char))
        .reverse()
        .join('');
    return alphabetsOnly;
};
console.log(reverseLettersOnly(str));
dlrowolleh

Testing with Different Inputs

function reverseLetter(str) {
    return str.split('')
        .reverse()
        .filter(val => /[a-zA-Z]/.test(val))
        .join('');
}

console.log(reverseLetter('abc123def'));    // "fedcba"
console.log(reverseLetter('Hello@World!'));  // "dlroWolleH"
console.log(reverseLetter('12345'));        // ""
console.log(reverseLetter('JavaScript'));   // "tpircSavaJ"
fedcba
dlroWolleH

tpircSavaJ

Conclusion

This approach effectively reverses alphabetic characters by combining array methods with regex filtering. The regex pattern /[a-zA-Z]/ ensures only letters are included in the final result.

Updated on: 2026-03-15T23:19:00+05:30

174 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements