Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery get random words from textarea

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.

like image 893
Stoyan Zdravkov Avatar asked Dec 15 '12 14:12

Stoyan Zdravkov


3 Answers

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

like image 167
Teneff Avatar answered Nov 19 '22 09:11

Teneff


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);
}
like image 27
WebStakker Avatar answered Nov 19 '22 10:11

WebStakker


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
like image 1
oleq Avatar answered Nov 19 '22 09:11

oleq