DEV Community

loading...

Discussion on: How to Reverse a String in JavaScript

Collapse
qm3ster profile image
Mihail Malo • Edited

Yet another ridiculous approach (requires node.js):

const input = "Input string lol.\nNicely done haha.\nLook at it go!"
const buf = Buffer.from(input,'latin1')
for (let l = buf.length; l>0;l--){
  for (let i=0;i<l-1;i++){
    buf.slice(i,i+2).swap16();
  }
}
const output = buf.toString('latin1')
console.log(input)
console.log(output)

Among the reasons it is ridiculous is the fact that Buffers inherit .reverse() from Uint8Array, so I could just use that.

Or:

const rev = input => {
  const buf = Buffer.from(input,'latin1')
  const len = buf.length
  let j
  for (let i=len;i>0;i--)
    buf.slice(i%2,-(i+len)%2||j).swap16()
  return buf.toString('latin1')
}