1

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?

GibboK
  • 71,848
  • 143
  • 435
  • 658
  • 5
    Why are you doing this with regular expressions, and not using the DOM to parse it as html? – David Thomas Jan 20 '15 at 14:47
  • I need it in order to create a html tree of random widgets in dojo. – GibboK Jan 20 '15 at 14:56
  • [Don't use regext to parse HTML. Just don't or Zalgo will eat you.](http://stackoverflow.com/a/1732454/237955) – amphetamachine Jan 20 '15 at 14:57
  • But that still doesn't explain why you're using regular expressions instead of DOM parsing. – David Thomas Jan 20 '15 at 17:13
  • @DavidThomas thanks for your comment. What I needed was to apply regex to a string containing HTML semantic before actually insertion in the page DOM. This was the reason why I could not use DOM parsing. – GibboK Jan 20 '15 at 22:12

1 Answers1

2

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);
Matteo Tassinari
  • 18,121
  • 8
  • 60
  • 81
  • could you please show me how I could replace the content of id and widgetid with a random number? – GibboK Jan 20 '15 at 14:52
  • please read my original question, it says: I need to replace id="XXX" and widgetid="XXX" with a random number... should I create a new question? Thanks for your help. – GibboK Jan 20 '15 at 14:55