The Final Act: Swapping Characters Back
Step 4: Initiate a Second Pass
After reversing our isolated "gold coins" (the alphabetical characters), it's time to go through the string again. This second round, starting from the beginning, has a different objective—swapping.
Step 5: Swap Using Position/Index
The plan is simple: replace the alphabetical characters in the original string with the reversed alphabetical characters from our newly created array, reversedAlpha
. Think of it like putting the gold coins back but in a new order.
How It Works
Imagine you have two buckets—one with the original gold coins and the other with the gold coins turned upside down (reversed). As you walk along the path where you initially picked the coins, you place the upside-down coins back in their original spots.
By following these steps, we effectively reverse only the alphabetical characters while keeping the non-alphabetical ones intact. It's as if the coins (alphabets) were flipped, while the pebbles (special characters) remained undisturbed.
1for (let i = 0; i < str.length; i++) {
2 if (/[a-zA-Z]/.test(str[i])) {
3 str[i] = reversedAlpha[i];
4 }
5}