shuffle a string in javascript

To shuffle a string in JavaScript, you can first convert the string to an array of characters, shuffle the array using a randomization technique, and then convert the shuffled array back to a string. Here's one possible implementation using the Fisher-Yates shuffle algorithm:

index.tsx
function shuffleString(str) {
  // Convert string to array of characters
  let arr = str.split("");
  
  // Fisher-Yates shuffle algorithm
  for (let i = arr.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * (i + 1));
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
  
  // Convert shuffled array back to string
  return arr.join("");
}

// Example usage
let str = "hello world";
let shuffled = shuffleString(str);
console.log(shuffled); // eowllhldro 
465 chars
19 lines

gistlibby LogSnag