Created
January 4, 2023 21:30
-
-
Save codebrainz/50a8ed7b127ebc83206a239b79da5565 to your computer and use it in GitHub Desktop.
Reversing a string in JS.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let str1 = "hello"; | |
let str2 = ""; | |
for (let i = str1.length - 1; i >= 0; i--) { | |
str2 += str1[i]; | |
} | |
console.log(str1, "=>", str2); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Uses an array since JS strings are immutable | |
let arr = Array.from("hello"); | |
let l = 0; | |
let r = arr.length - 1; | |
while (l < r) { | |
const c = arr[l]; | |
arr[l++] = arr[r]; | |
arr[r--] = c; | |
} | |
console.log(arr.join("")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment