phpjavascriptfunctionshufflephpjs

str_shuffle() equivalent in javascript?


Like the str_shuffle() function in PHP, is there a function similar in shuffling the string in javascript ?

Please help !


Solution

  • No such function exist, you'll write one yourself. Here's an example:

    function shuffle(string) {
        var parts = string.split('');
        for (var i = parts.length; i > 0;) {
            var random = parseInt(Math.random() * i);
            var temp = parts[--i];
            parts[i] = parts[random];
            parts[random] = temp;
        }
        return parts.join('');
    }
    
    alert(shuffle('abcdef'));