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"))
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Another solution using for loop, but only iterates half the time.