Computer >> Computer tutorials >  >> Programming >> Javascript

Reversing alphabets in a string using JavaScript


Problem

We are required to write a JavaScript function that takes in a string, str, which consists of alphabets and some special characters.

Our function should return a new string based on the input string where all characters that are not alphabets stay in the same place, and all letters reverse their positions.

For example, if the input to the function is

Input

const str = 'k_lmn_opq';

Output

const output = 'q_pon_mlk';

Example

const str = 'k_lmn_opq';
const reverseAlphabets = (str) => {
   const arr = str.split('')
   let left = 0
   let right = arr.length - 1
   const swap = (a, b) => {
      const temp = arr[a]
      arr[a] = arr[b]
      arr[b] = temp
   }
   const isLetter = (x = '') => /[a-zA-Z]/.test(x)
   while (left <= right) {
   while (!isLetter(arr[left])) {
      left += 1
      if (left > right) {
         break
      }
   }  
   while (!isLetter(arr[right])) {
      right -= 1
      if (left > right) {
         break
      }
   }
      if (left > right) {
      break
   }
      swap(left, right)
      left += 1
      right -= 1
   }
   return arr.join('')
};
console.log(reverseAlphabets(str));

Output

q_pon_mlk