1

I'm trying to randomize the words in a string using jquery but my code doesn't return anything.

This is what I have so far:

function makerand() {


  var text = "";
  var possible = "david, sarah, michelle, pedro";

   text += possible.charAt(Math.floor(Math.random() * possible.length));

  return text;

  alert(text);
}

html:

<button onclick="makerand()">click me</button>

what I need to do is to randomize that string like so for example:

sarah, pedro, michelle, david

Could someone please advise on this?

David Hope
  • 1,426
  • 4
  • 21
  • 50

2 Answers2

1

Split the string into an array like so:

var items = possible.split(", ");

Then shuffle the array like so: How to randomize (shuffle) a JavaScript array?

Then rejoin the elements:

possible.join(", ")

Ezz
  • 534
  • 2
  • 8
  • 17
1

Split the String by comma. You get an array back and then sort the array by giving random.

var possible = "david, sarah, michelle, pedro";

var result = possible.split(", ").sort(function() {
    return 0.4 - Math.random()
}).join(", ");

console.log(result)
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307