请更改此行:
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