If you have a string "abcdef", how would you go about reversing pairs so it would look like "badcfe"? If the string has an odd number of characters, leave the last character in place.
I am aware of x.spilt('').reverse().join('')
to reverse an entire string but couldn’t figure out the above stated.
CodePudding user response:
You can just use a simple for-loop:
function reversePairs(str) {
let ret = "";
for (let i = 0; i < str.length; i = 2) {
ret = str.substring(i, i 2).split('').reverse().join('');
}
return ret;
}
const str = 'abcdef';
console.log(reversePairs(str))
CodePudding user response:
You can do with the same solution you mentioned in the question, but the approach of loop should be diffrent.
You can take this as reference