Method 3: Modern Elegance with ES6 and Beyond
Step 1: Extract Only the Alphabets
In this method, we're tapping into the powerful arsenal of ES6 methods, specifically map and filter, to craft a more streamlined solution.
Creating an Alphabetic Array
First off, we extract only the alphabetical characters from the string and store them in a new array, which we'll call alphaOnly.
Here's how you can do it in multiple languages:
1let alphaOnly = str.split('').filter(c => /[a-z]/gi.test(c));Step 2: The Transformation Act
After creating our alphaOnly array, the next phase is where the real magic happens. We'll split the original string into an array and perform a transformation using map.
Returning Non-Alphabetic Characters
During this transformation, if a character does not match our Regular Expression criteria (i.e., it's not an alphabetical character), we simply return it in its current position, leaving it untouched.
Picture this as walking through a garden and only flipping the stones that have a specific marking, while leaving all others in their original state.
xxxxxxxxxxlet alphaOnly = str.split('').filter(c => /[a-z]/gi.test(c)); return str.split('').map( c => { if (/[^a-z]/gi.test(c)) { return c; }});

