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.
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/
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With