Reputation: 15
I'm writing a JavaScript function that looks at a webpage and replaces every instance of a price with a random string from an array I made. Each time I run my script on a webpage a different string is chosen from the array, but it chooses the same string for every instance of the replace method. How can I have each replace pick a random number? I actually had this working at one point but I had to change my code and now it repeats the same string.
Here is my code:
$("*").each( function() { //go through each paragraph
var curr = $(this).html();
var price = Math.floor(Math.random() * pricesArray.length);
curr = curr.replace(/(\$[0-9]+\.[0-9]{2})+/g, pricesArray[price]);
console.log(curr);
$(this).html(curr); //update paragraph text
});
Upvotes: 0
Views: 64
Reputation: 36448
$('*')
will match <html>
, <body>
, etc. The first match (<html>
) will perform the replacement on all prices in the page, since they're all contained within. Assuming the random string is not also a price, that's it, nothing left to replace.
You can do this instead by calling a replacement function for each match, instead of picking a new string for each node:
var pricesArray = ['thing one', 'thing two', 'thing three', 'thing four'];
var text = document.body.innerHTML;
text = text.replace(/(\$[0-9]+\.[0-9]{2})+/g,
function() {
var repno = Math.floor(Math.random() * pricesArray.length);
return pricesArray[repno];
}
);
document.body.innerHTML = text;
<p>$5.99</p>
<p><b>$7.97</b></p>
<p>A price ($14.92) within some text, followed by another price ($17.76).</p>
Upvotes: 1