my question is very simple but i cant figure it out how to do it.
I have a textarea with some text and I want to get 5 random words from text and put them in another input field (automatic). I dont want to be specific words. Random 5 words. That's it. Thanks!
Example:
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
Input field that contains when this text is writed let's say: ipsum, amet, veniam, velit, deserunt.
This is my suggestion for the work flow:
example code:
var text = "Lorem ipsum ......";
var words = $.unique(text.match(/\w+/mg));
var random = [];
for(var i=0; i<5; i++) {
var rn = Math.floor(Math.random() * words.length);
random.push( words[rn]);
words.splice(rn, 1);
}
alert( random ):
working example in jsFiddle
This should work:
var content = $("#myTextarea").val(),
words = content.split(" ");
var randWords = [],
lt = words.length;
for (var i = 0; i < 5; i++)
randWords.push(words[Math.floor(Math.random() * lt)]);
$("#otherField").val(randWords.join(" "));
EDIT: To prevent duplicates, you can use the following:
var nextWord;
for (var i = 0; i < 5; i++)
{
nextWord = words[Math.floor(Math.random() * lt)];
if (("|" + randWords.join("|") + "|").indexOf("|" + nextWord + "|") != -1)
{
i--;
continue;
}
randWords.push(nextWord);
}
Even shorter:
var str = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt.';
function rWords( t ) {
for ( var i = 5, s = t.match( /(\d|\w|')+/g ), r = [] ; i-- ; r.push( s[ Math.random() * s.length | 0 ] ) );
return r.join( ', ' ).toLowerCase();
}
console.log( rWords( str ) );
> lorem, eiusmod, elit, dolor, do
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