首页 > 解决方案 > 如何交换字符串 JavaScript 中的字符位置

问题描述

我正在制作一个解密功能,但我被困在需要交换字符串的第二个字母和最后一个字母的位置的部分。 我也尝试过使用替换方法,但我认为应该使用子字符串。

Hello 应该等于 Holle 等

function decipher(str) {
  let s = ""
  for (let word of str.split(" ")){
    let dig = word.match(/\d+/)[0]
    word = word.replace(dig, String.fromCharCode(dig))
    let secondLetter = word[1]
    let lastLetter = word[word.length - 1]
    let swapped = word.substring(0,1) + lastLetter + word.substring(2,3) + secondLetter
    s += swapped + " "
  }
  return s
}; 

标签: javascriptstringreplacesubstringswap

解决方案


请更改此行:

let swapped = word.substring(0,1) + lastLetter + word.substring(2,word.length - 1) + secondLetter;

推荐阅读