reverse a string in place in javascript

To reverse a string in place using javascript, you can convert the string to an array, reverse the array, and then convert it back to a string. Here's an example:

index.tsx
function reverseStringInPlace(str) {
  // convert string to array
  let arr = str.split("");
  
  // reverse the array in place
  for (let i = 0; i < arr.length / 2; i++) {
    let temp = arr[i];
    arr[i] = arr[arr.length - 1 - i];
    arr[arr.length - 1 - i] = temp;
  }
  
  // convert array back to string
  return arr.join("");
}

// example usage
let reversedStr = reverseStringInPlace("hello world");
console.log(reversedStr); // "dlrow olleh"
452 chars
19 lines

In this example, the reverseStringInPlace function takes a string str as input, converts it to an array using the split method, reverses the array in place using a for loop, and then converts the reversed array back to a string using the join method. The reverse method is not used here because it creates a new array and does not reverse the original array in place.

gistlibby LogSnag