简体   繁体   中英

How do I reverse a string by character instead of flipping the whole string?

If the string is "hello world", I need to flip every pair of characters and return "ehll oowlrd". The way I do it returns "olleh dlrow".

var flipPairs = function (string) {

  return string.split("").reverse().join("");

}

console.log(flipPairs("hello world")); // -> ehll oowlrd

I'd use a regular expression - match two consecutive characters, and replace with them in reversed order:

 const flipPairs = str => str.replace(/(.)(.)/g, '$2$1'); console.log(flipPairs("hello world"));

What about this:

 function flip(s) { let r = ""; for (let i = 0; i < s.length; i+=2) r += (i+1 < s.length ? s[i+1] : "")+s[i]; return r; } console.log(flip("hello world"));

You could calculate the index and take this character of the actual one if the string has an odd length.

 function flipPairs(string) { return [...string].map((c, i, a) => a[i + ((i + 1) % 2 || -1)] || c).join(''); } console.log(flipPairs('hello world'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM