Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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:
- split('') - Converts the string into an array of characters
- reverse() - Reverses the order of all characters
-
filter() - Keeps only alphabetic characters using regex pattern
/[a-zA-Z]/ - 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.
Advertisements
