使用 JavaScript 反转字符串中的字母
问题
我们需要编写一个JavaScript函数,它接受一个字符串str,它由字母和一些特殊字符组成。
我们的函数应该根据输入字符串返回一个新字符串,其中所有不是字母的字符都保留在同一个位置,并且所有字母都颠倒了它们的位置。
例如,如果函数的输入是
输入
const str = 'k_lmn_opq';
输出
const output = 'q_pon_mlk';
示例
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));输出结果q_pon_mlk
