Skip to content
Advertisement

How do I shuffle the characters in a string in JavaScript?

In particular, I want to make sure to avoid the mistake made in Microsoft’s Browser Choice shuffle code. That is, I want to make sure that each letter has an equal probability of ending up in each possible position.

e.g. Given “ABCDEFG”, return something like “GEFBDCA”.

Advertisement

Answer

I modified an example from the Fisher-Yates Shuffle entry on Wikipedia to shuffle strings:

String.prototype.shuffle = function () {
    var a = this.split(""),
        n = a.length;

    for(var i = n - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }
    return a.join("");
}
console.log("the quick brown fox jumps over the lazy dog".shuffle());
//-> "veolrm  hth  ke opynug tusbxq ocrad ofeizwj"

console.log("the quick brown fox jumps over the lazy dog".shuffle());
//-> "o dt hutpe u iqrxj  yaenbwoolhsvmkcger ozf "

More information can be found in Jon Skeet’s answer to Is it correct to use JavaScript Array.sort() method for shuffling?.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement