我有以下测试字符串,我需要替换id="XXX"
并widgetid="XXX"
使用一个随机数。
var test = '<div id="1566" widgetid="1566"></div><div id="1567" widgetid="1568"></div>';
你能给我个正则表达式吗?
您可以尝试类似
/ (?:widget)?id="(\d+)"/ig
像这样
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);
}
替换为随机数,您可以执行以下操作:
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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句