DEV Community

loading...

Discussion on: Reverse a String - Four JavaScript Solutions

Collapse
nsriram profile image
Sriram Narasimhan

Another solution using for loop, but only iterates half the time.

function reverse(str){
  let reversedStr = str
  const length = reversedStr.length
  for(i=0; i< length/2; i++){
    const endIndex = length - (i+1)
    if(endIndex > i){
      const pre = reversedStr.substring(0, i)
      const beginChar = reversedStr.substring(i, i+1)
      const unsorted = reversedStr.substring(i+1,endIndex)
      const endChar = reversedStr.charAt(endIndex)
      const post = reversedStr.substring(endIndex+1)

      //An overkill of swap !
      reversedStr = pre+endChar+unsorted+beginChar+post         
    }
  }
  return reversedStr
}

console.log(reverse("1234567"))
console.log(reverse("123456"))
console.log(reverse("abracadabra"))
console.log(reverse("esrever"))