views:

58

answers:

4

Hello,

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

Please help !

A: 

No, there is no inbuilt method of String that will randomise the character sequence.

Jon Cram
+1  A: 

You could use php.js implementation: http://phpjs.org/functions/str_shuffle:529

Mewp
+1  A: 

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'));
BalusC
BTW, this is the Fisher–Yates shuffle: http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
Álvaro G. Vicario
A: 

Here's my versinof the php.js function

function str_shuffle (str) {

    var newStr = [];

    if (arguments.length < 1) {
        throw 'str_shuffle : Parameter str not specified';
    }

    if (typeof str !== 'string') {
        throw 'str_shuffle : Parameter str ( = ' + str + ') is not a string';
    }

    str = str.split (''); 
    while (str.length) {
        newStr.push (str.splice (Math.floor (Math.random () * (str.length - 1)) , 1)[0]);
    }

    return newStr.join ('');
}
Hans B PUFAL