Skip to content

Instantly share code, notes, and snippets.

@codebrainz
Created January 4, 2023 21:30
Show Gist options
  • Save codebrainz/50a8ed7b127ebc83206a239b79da5565 to your computer and use it in GitHub Desktop.
Save codebrainz/50a8ed7b127ebc83206a239b79da5565 to your computer and use it in GitHub Desktop.
Reversing a string in JS.
let str1 = "hello";
let str2 = "";
for (let i = str1.length - 1; i >= 0; i--) {
str2 += str1[i];
}
console.log(str1, "=>", str2);
// 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