mercredi 31 janvier 2018

How to get a random number each time the code is executed for replace?

I apologize if this is a repeat question - I've been sifting through "random" questions but none of the answers I've found have helped.

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
});

Thank you!




Aucun commentaire:

Enregistrer un commentaire