regex - How do I replace every dash (-) with a random number in javascript? -
i have have codes abcde-----abcd----abc--, each (-) needs random number.
i have no problem using replace function change single dash random number, have no clue how make each dash random number. note: each number doesn't need unique.
here now, need numbers not same. http://jsfiddle.net/oqrstsdm/
var minnumber = 1; var maxnumber = 9; randomnumberfromrange(minnumber, maxnumber); function randomnumberfromrange(min, max) { var number = (math.floor(math.random() * (max - min + 1) + min)); var str = "abcde-----fgabc--"; var res = new regexp("-", "g"); var code = str.replace(res, number); document.getelementbyid("ccode").innerhtml = "code: " + code; }
you use function second argument in string.prototype.replace()
.
var str = "abcde-----fgabc--"; var code = str.replace(/-/g, function() { return math.floor(math.random() * (max - min + 1)) + min; });
Comments
Post a Comment