如何在字符串 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
}; 
q5070212 回答:如何在字符串 JavaScript 中交换字符位置

请更改此行:

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

您可以解构字符串:

const swap = ([a,b,...xs]) => [a,xs.pop(),...xs,b].join('');
//                                  ^^^^^^^^         ^
//                                  |____swapping____|

swap("Hello");
//=> "Holle"

通过解构,您还将支持表情符号(但可能不是字素)之类的东西:

swap("H?ll?");
//=> "H?ll?"

交换字符串中的单词:

const decipher = str => str.split(' ').map(swap).join(' ');

decipher("Hello World");
//=> "Holle Wdrlo"

decipher(decipher("Hello World"));
//=> "Hello World"

为什么要解构?

通过索引或(简单)正则表达式读取字符串中的字符可能不适用于多代码点字符,例如(但不限于)表情符号:

"?".length;
//=> 2! Not 1.

"?".charAt(0);
//=> "\ud83c"! Not "?".

考虑这个 swap 函数:

function swap(str) {
  var arr = str.split('');
  var [a,b] = [arr[1],arr[arr.length-1]];
  arr[1] = b;
  arr[arr.length-1] = a;
  return arr.join('');
}

适用于普通的旧 ASCII:

swap("Hello");
//=> "Holle"

不能像您期望的那样使用表情符号:

swap("H?ll?");
//=> "H\udf63\udf2fll\ud83c\ud83c"
,

考虑将其提取到一个函数中以保持更干净的代码库:

function swapSecondAndLastLetter(str) {
   // Split the string into a mutable array
   let original = str.split('');

   original[1] = str[str.length-1];
   original[original.length-1] = str[1];

   // Join the mutable array back into a string
   return original.join('');
}
,

如果仅用于特定用例(即交换第二个和最后一个),您可以使用简单的正则表达式 -

正则表达式 -(.)(.)(.*)(.)

const str = "Hello";
console.log(swap(str));

function swap() {
  return str.replace(/(.)(.)(.*)(.)/,"$1$4$3$2")
}

本文链接:https://www.f2er.com/10069.html

大家都在问