我的输入是:'z<*zj'
;我正在查看输出为:j<*zz
;
在这个字符串中,特殊字符的位置没有改变。但字母排列颠倒了。我正在尝试获得输出,但没有成功。
有人帮我找到最短、最正确的方法吗?
我的尝试:
const Reverser = (str) =>{
return str.replace(/[a-zA-Z]+/gm, (item) => {
return item.split('')[0].split('')
});
}
const result = Reverser('z<*zj');
console.log(result);
提前感谢
不确定我是否正确理解你
但我想你只想对字母排序而不想更改非字母
这是我的方法:
const Reverser = (str) => {
// create sorted array of all letters found
// first remove all non-letters, then split into array
// then sort in reverse so that we can use fast .pop() instead of slow .shift()
let letters = str.replace(/[^a-zA-Z]+/gm, '').split('').sort().reverse();
// find letters and replace them with those in array, one by one
return str.replace(/[a-zA-Z]/gm, () => {
return letters.pop();
});
}
console.log(Reverser('z<*zj')); // j<*zz
console.log(Reverser('xy-a=cb')); // ab-c=xy