Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split words & shuffle / jumble letters

I am trying to shuffle words. I Want to shuffle First with its respective alphabets. Currently it is shuffling First with Second alphabets..

I Want to split words & shuffle "sFtir Seocdn".

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("");
}


alert("First Second".shuffle());

I tried splitting by below code, but then it only splits & shuffles words not letters.

var a = this.split(" "),
return a.join(" ");

Jsfiddle link : http://jsfiddle.net/9L8rs/1/ Pls suggest what should I do.

like image 466
itsMe Avatar asked Dec 25 '22 07:12

itsMe


2 Answers

Just split the string into words and shuffle the letters in words separately:

"First Second".split(' ').map(function(w) { return w.shuffle(); }).join(' ');

Here .split and .map (polyfill may be applied for old browsers) methods can help.

DEMO: http://jsfiddle.net/9L8rs/2/

like image 108
VisioN Avatar answered Jan 06 '23 09:01

VisioN


Try splitting the incoming String first:

String.prototype.shuffle = function() {
    return this.split(" ").map(function(word, i) {
        var a = word.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("");
    }).join(" ");
}

alert("First Second".shuffle());

Updated JSFiddle

like image 39
reaxis Avatar answered Jan 06 '23 08:01

reaxis