How to shuffle characters in a String using JavaScript

← PrevNext →

There are few simple methods to shuffle characters in a string using JavaScript. I’ll show you two different methods here to shuffle string characters and at the end using a similar method I’ll show you how to shuffle an array of values.

1st Method

<script>
  let shuffle = (s) => {
    let arr = s.split(''), arr_len = arr.length;
    
    while (arr_len) {
      let rnd = Math.floor(Math.random() * arr_len--);
      [arr[arr_len], arr[rnd]] = [arr[rnd] , arr[arr_len]];
    }
    
    let str = arr.join('');
    document.write (str);	// show shuffled characters.
  }

  shuffle('Hello world I am Arun Banik ☺');
</script>
Try it

I am first splitting the string (separates each character using comma) and stores it in an array. The above string will look like this after splitting.

(29) ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', ' ', 'I', ' ', 'a', 'm', ' ', 'A', 'r', 'u', 'n', ' ', 'B', 'a', 'n', 'i', 'k', ' ', '☺']

Next, using the while loop, I am sorting each character randomly and storing it back in the array.

Finally, I’ll remove the commas using join('') method and show the shuffled string.

2nd Method

Here’s another method to shuffle characters in a string using split(), sort() and join() methods. It’s a one liner code and its very useful.

<script>
  let shuffle = (s) => {
    let str = s.split('')
      .sort(() => 0.5 - Math.random())
      .join('');
    
    document.write (str);   // show shuffled characters.
  }

  shuffle('Hello world I am Arun Banik ☺');
</script>
Try it

Similar style of execution, like the 1st method. Its splits the string, sorts the characters randomly and finally removes the commas (using join() method).

Shuffle Array values

This is bonus. Now lets apply one of the above methods on an array and see if we can shuffle the values randomly.

<script>
  const arr = ['alpha', 'bravo', 'charlie', 'delta', 'echo'];
  
  let shuffle_array = () => {
    let arr_len = arr.length, rnd_i;
    
    while (arr_len) {
      let rnd_i = Math.floor(Math.random() * arr_len--);
      [arr[arr_len], arr[rnd_i]] = [arr[rnd_i] , arr[arr_len]];
    }
    
    document.write (arr);   // show shuffled array values.
  }

  shuffle_array();
</script>
Try it

Cool!. If you want you can remove the commas using the .join() method like this:

document.write(arr.join(' '));

That's it.

← PreviousNext →