简体   繁体   English

Javascript - 正则表达式:如何用相同的id加号替换字符串中的id?

[英]Javascript - Regex : How to replace id in string with the same id plus number?

I have a string with multiple elements with id's like below: 我有一个包含多个元素的字符串,其ID如下所示:

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: 现在我正在使用这个正则表达式来查找字符串中的所有id:

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

Afterwards I want to replace all those id's with a new id. 之后我想用新的id替换所有那些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. 我想要reg2 ,如上所示,返回id的值。 I'm not too familiar with Regular Expressions, so how can I go about doing this? 我不太熟悉正则表达式,所以我该怎么做呢?

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/ 演示: 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. 这将检查id是否在第一个位置设置,然后才会修改它。

Also, it is safe in case the HTML contains a comment node (where IE 6-8 does include comment nodes in .children ). 此外,如果HTML包含注释节点(IE 6-8确实包含.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. 但是在我的小提琴中,我嵌套<input />并且它仍然被修改。

To get the get the updated HTML, use div.innerHTML . 要获取更新的HTML,请使用div.innerHTML

With jQuery, you can try: 使用jQuery,您可以尝试:

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/ 演示: 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. 虽然id以和/或数字开头是有效的,但您应该将元素的id更改为普通标识符。

References: 参考文献:

尝试使用

.replace(/id='(.*?)'/g, 'id="$1_' + numCompare + '"');

Using jQuery (further to your commments). 使用jQuery(进一步到您的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). 这比在HTML上使用正则表达式要好得多( 使用正则表达式解析HTML:为什么不呢? ),速度更快(虽然可以通过使用比$("[id]")更直接的选择器来进一步改进,例如给出元素一类)。

Fiddle: http://jsfiddle.net/georeith/E6Hn7/10/ 小提琴: http//jsfiddle.net/georeith/E6Hn7/10/

Regex probably isn't the right way to do this, here is an example that uses jQuery: 正则表达式可能不是正确的方法,这是一个使用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/ 示例: http//jsfiddle.net/fYb3U/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM