7
votes

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.

3
This is pretty straight forward -> FIDDLEadeneo
Ok, it's work in jsfiddle.net/cwrxV but when i try to put in my site it wont work! What's the problem, please help me to figure it out. Thanks for previous posts. My HTML code is equal to this that i pasted in jsfiddle and i load jquery code from <head>, from <body>, from external js file. Result is the same... :/Stoyan Zdravkov

3 Answers

4
votes

This is my suggestion for the work flow:

  1. Get the words from the textarea
  2. Remove duplicates
  3. Iterate the array get the word and remove it from the array (avoid duplicates)

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

4
votes

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);
}
1
votes

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