3

I have a string with multiple elements with id's like below:

var data = "<div id='1'></div><input type='text' id='2'/>";

Now I'm using this regex to find all the id's in the string:

var reg = /id="([^"]+)"/g;

Afterwards I want to replace all those id's with a new id. Something like this:

data = data.replace(reg, + 'id="' + reg2 + '_' + numCompare + '"');

I want reg2, as seen above, to return the value of the id's. I'm not too familiar with Regular Expressions, so how can I go about doing this?

Daniel Daranas
  • 22,454
  • 9
  • 63
  • 116
Phillip-juan
  • 546
  • 4
  • 29

4 Answers4

5

Instead of using regex, parse it and loop through elements. Try:

var data = "<div id='1'></div><div id='asdf'><input type='text' id='2'/></div>",
    numCompare = 23,
    div = document.createElement("div"),
    i, cur;

div.innerHTML = data;

function updateId(parent) {
    var children = parent.children;
    for (i = 0; i < children.length; i++) {
        cur = children[i];
        if (cur.nodeType === 1 && cur.id) {
            cur.id = cur.id + "_" + numCompare;
        }
        updateId(cur);
    }
}

updateId(div);

DEMO: http://jsfiddle.net/RbuaG/3/

This checks to see if the id is set in the first place, and only then will it modify it.

Also, it is safe in case the HTML contains a comment node (where IE 6-8 does include comment nodes in .children).

Also, it walks through all children of all elements. In your example, you only had one level of elements (no nested). But in my fiddle, I nest the <input /> and it is still modified.

To get the get the updated HTML, use div.innerHTML.

With jQuery, you can try:

var data = "<div id='1'></div><div id='asdf'><input type='text' id='2'/></div>",
    numCompare = 23,
    div = $("<div>"),
    i, cur;

div.append(data);

div.find("[id]").each(function () {
    $(this).attr("id", function (index, attr) {
        return attr + "_" + numCompare;
    });
});

DEMO: http://jsfiddle.net/tXFwh/5/

While it's valid to have the id start with and/or be a number, you should change the id of the elements to be a normal identifier.

References:

Ian
  • 50,146
  • 13
  • 101
  • 111
2

Try using

.replace(/id='(.*?)'/g, 'id="$1_' + numCompare + '"');
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
1

Using jQuery (further to your commments).

var data = "<div id='1'></div><input type='text' id='2'/>";
var output = $("<div></div>").html(data); // Convert string to jQuery object
output.find("[id]").each(function() { // Select all elements with an ID
   var target = $(this);
   var id = target.attr("id"); // Get the ID
   target.attr("id", id + "_" + numCompare); // Set the id
});
console.log(output.html());

This is much better than using regex on HTML (Using regular expressions to parse HTML: why not?), is faster (although can be further improved by having a more direct selector than $("[id]") such as giving the elements a class).

Fiddle: http://jsfiddle.net/georeith/E6Hn7/10/

Community
  • 1
  • 1
George Reith
  • 13,132
  • 18
  • 79
  • 148
1

Regex probably isn't the right way to do this, here is an example that uses jQuery:

var htmlstring = "<div id='1'></div><input type='text' id='2'/>";

var $dom = $('<div>').html(htmlstring);

$('[id]', $dom).each(function() {
    $(this).attr('id', $(this).attr('id') + '_' + numCompare);
});

htmlstring = $dom.html();

Example: http://jsfiddle.net/fYb3U/

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306