My Input is this: 'z<*zj'
;
I am looking a Output as : j<*zz
;
here in this string, special characters not changed in position. But the letters arranged reversed alphabets. I am trying to get the output, but not works.
any one help me with shortest and correct way to get this?
my try:
const Reverser = (str) =>{ return str.replace(/[a-zA-Z]+/gm, (item) => { return item.split('')[0].split('') }); } const result = Reverser('z<*zj'); console.log(result);
Thanks in advance
Advertisement
Answer
Not sure if I understand you correctly.
But I think you want to sort only the letters without changing non-letters?
Here is my approach:
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