Javascript - Regex : How to replace id in string with the same id plus number? -
i have string multiple elements id's below:
var data = "<div id='1'></div><input type='text' id='2'/>";
now i'm using regex find id's in string:
var reg = /id="([^"]+)"/g;
afterwards want replace id's new id. this:
data = data.replace(reg, + 'id="' + reg2 + '_' + numcompare + '"');
i want reg2
, seen above, return value of id's. i'm not familiar regular expressions, how can go doing this?
instead of using regex, parse , 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; (i = 0; < 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 see if id
set in first place, , modify it.
also, safe in case html contains comment node (where ie 6-8 include comment nodes in .children
).
also, walks through children of elements. in example, had 1 level of elements (no nested). in fiddle, nest <input />
, still modified.
to get updated html, use div.innerhtml
.
with jquery, 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 have id
start and/or number, should change id
of elements normal identifier.
references:
.children
: https://developer.mozilla.org/en-us/docs/dom/element.children.nodetype
: https://developer.mozilla.org/en-us/docs/dom/node.nodetypejquery.find()
: http://api.jquery.com/find/jquery.attr()
: http://api.jquery.com/attr/jquery.each()
: http://api.jquery.com/each/
Comments
Post a Comment