How to shuffle characters of a string in JavaScript

In this tute, we will discuss how to shuffle characters of a string in JavaScript. Before getting into the topic, let’s see what is a string in JavaScript.

The JavaScript string is zero or more characters enclosed within quotes. Few examples of strings are,

var s1 = 'abcd';           // String with alphabets
var s2 = '12345';          // String with digits
var s3 = '+-=*';           // String with special characters
var s4 = 'H3llo w0rld!';

Shuffle characters of a JavaScript String

There are many ways to shuffle characters of a string in JavaScript. Let’s see two commonly used methods in here. Since strings are immutable, we will be converting the string into an array and then shuffle it. Later, we’ll convert it back to a string. We’ll use split() and join() for doing this.

Method 1:

In this method, we will define a new function called shuffle(). This function will use the Math.random() function to get a random index and swap those elements to shuffle randomly.

Algorithm:

  1. Firstly, convert the string into an array using the split() method.
  2. After that, iterate through all the indices in the array.
  3. At each index, generate a random index to swap with by using Math.random() method.
  4. To swap the elements at indices i and j, create a new variable temp and store the value at arr[j] in this.
  5. Then save the arr[i] value in arr[j].
  6. Save the temp value in arr[i].
  7. Convert the shuffled array back to a string using the join() method.
  8. In the end, return the shuffled string.

Pseudocode:

function shuffle(s):
    arr = stringToArray(s)
    for i in [0, n-1]:
        j = getRandomInt(n)
        temp = arr[i]
        arr[i] = arr[j]
        arr[j] = temp
    s = arrayToString(arr)
    return s

Code Snippet

Below is our JavaScript code:

function getRandomInt(n) {
  return Math.floor(Math.random() * n);
}
function shuffle(s) {
  var arr = s.split('');           // Convert String to array
  var n = arr.length;              // Length of the array
  
  for(var i=0 ; i<n-1 ; ++i) {
    var j = getRandomInt(n);       // Get random of [0, n-1]
    
    var temp = arr[i];             // Swap arr[i] and arr[j]
    arr[i] = arr[j];
    arr[j] = temp;
  }
  
  s = arr.join('');                // Convert Array to string
  return s;                        // Return shuffled string
}

var s = 'ABCDEF';

s = shuffle(s);

console.log(s);

Output:

BEDACF

 

Method 2:

In this method, we will make use of methods like sort()Math.random(). The algorithm used to shuffle characters of a string is:

Algorithm:

  1. Firstly, convert the string into an array using the split() method.
  2. Then, call the sort() method of the array.
  3. In its function definition, return a random value (-ve, 0, +ve) each time it is called.
  4. After that, onvert the shuffled array back to a string using the join() method.
  5. In the end, return the shuffled string.

Pseudocode:

function shuffle(s):
    arr = stringToArray(s)
    arr.sort(function() {
        return 0.5-Random(0, 1)
    })
    s = arrayToString(arr)
    return s

Code Snippet:

function shuffle(s) {
  var arr = s.split('');           // Convert String to array
  
  arr.sort(function() {
    return 0.5 - Math.random();
  });  
  s = arr.join('');                // Convert Array to string
  return s;                        // Return shuffled string
}

var s = 'ABCDEF';

s = shuffle(s);

console.log(s);

Output:

FEBDCA

 

Finally, If you have any queries or doubts on how to shuffle characters of a string in JavaScript, simply comment in the comment section provided below.

Related posts:

One response to “How to shuffle characters of a string in JavaScript”

  1. Rex says:

    Is it possible to do this by hitting a button?

Leave a Reply

Your email address will not be published. Required fields are marked *