Reputation: 73938
I have the following string of test, I need to replace id="XXX"
and widgetid="XXX"
with a random number.
var test = '<div id="1566" widgetid="1566"></div><div id="1567" widgetid="1568"></div>';
Could yuou suggest me a regular expression?
Upvotes: 1
Views: 446
Reputation: 18584
You could try something like
/ (?:widget)?id="(\d+)"/ig
like this
var regex = /(?:widget)?id="(\d+)"/g;
var test = '<div id="1566" widgetid="1566"></div><div id="1567" widgetid="1568"></div>';
while((result = regex.exec(test)) != null) {
console.log(result);
}
to replace with random number, you could do:
function random(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
var regex = /((?:widget)?id)="(\d+)"/g;
var test = '<div id="1566" widgetid="1566"></div><div id="1567" widgetid="1568"></div>';
var new_string = test;
while((result = regex.exec(test)) != null) {
new_string = new_string.replace(result[0], result[1] + '="' + random(1, 9999) + '"');
}
console.log(new_string);
Upvotes: 2