Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - random .replace() error

I have problem with random .replace(), it allways display same random number, i am trying to replace $random$ with a different random number.

$(document).ready(function() {
  var arr = [
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    '10'
  ]
  $("#present-users").children('li.present-user').each(function() {
    arr.push($(this).find('img')[0].title);
  });
  var random = arr[Math.floor(Math.random() * arr.length)];
  var text = "$random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$ $random$".replace(/\$random\$/g, random);
  alert(text)
});

jsfiddle example

Thanks, Nikola

like image 289
NiKoLaPrO Avatar asked Apr 21 '26 11:04

NiKoLaPrO


2 Answers

One solution is to use the .replace(regex, function) overload:

str.replace(/\$random\$/g, function() {
    return arr[Math.floor(Math.random() * arr.length)];
});

Updated Fiddle

like image 63
Stryner Avatar answered Apr 23 '26 02:04

Stryner


You are calling Math.random() only once, and using this answer several times.

One way to fix this would be to make random a function, e.g.

var arr = [10,20,30];
var random = function(){return Math.floor(Math.random() * arr.length)};
alert(random());
alert(random());
alert(arr[random()]);
like image 35
CooncilWorker Avatar answered Apr 23 '26 00:04

CooncilWorker