JQuery gets random words from textarea

My question is very simple, but I cannot figure out how to do this.

I have a text area with some text, and I want to get 5 random words from the text and put them in another input field (automatically). I do not want to be specific words. Random 5 words. It. Thanks!

Example:

"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tem incididunt ut labore et dolore magna aliqua. Announcement announcement minim veniam, quis nostrud Gym ullamco laboris nisi ut aliquip ex ea commodo. Duis aute irure dolor to represent velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat irrelevant, lit culpa qui officia deserunt mollit anim id est laborum. "

An input field containing when this text is issued allows you to say: ipsum, amet, veniam, velit, deserunt.

+7
source share
3 answers

This is my suggestion for workflow:

  • Get words from text field
  • Remove duplicates
  • Iterate the array, get the word and remove it from the array (avoid duplicates)

code example:

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
source

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 duplication, 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); } 
+4
source

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 
+1
source

All Articles