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
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
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()]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With