在$ .each()中搜索和替换

时间:2015-06-03 21:32:19

标签: javascript jquery regex

我有下面的代码循环遍历DOM的一部分,搜索3个不同的字符串,并用其他东西替换每个字符串。我需要做到这一点,以便可以搜索和替换任意数量的项目,而不仅仅是3.是否可以使用jQuery?

function getDomArray(domClone){
    var postRows = [];

    $(domClone).each(function () {
        var find1 = "__hidden__";
        var find2 = "__bigtext__";
        var find3 = "col-sm-12";
        var re1 = new RegExp(find1, "g");
        var re2 = new RegExp(find2, "g");
        var re3 = new RegExp(find3, "g");

        $(this).html(function (index, html) {
            return html.replace(re1, '').replace(re2, 'bigtext').replace(re3, "col-sm-4");
        });
        postRows.push($($(this).html()).encodeHtml());  
    });

    return postRows;
}

更新1 :@ JonathanCard的答案中的代码会引发此错误:

  

无法阅读财产'替换'未定义的

请参阅此jsFiddle:http://jsfiddle.net/jsFiddlePlayer/vhg7csb7/12/

更新2 :答案中的代码有效!

1 个答案:

答案 0 :(得分:2)

试试这个:

function getDomArray(domClone) { var postRows = [];
    list_to_replace = {"__hidden__": '', "__bigtext__": "bigtext", "col-sm-12": "col-sm-14"};
    $(domClone).each(function() {
        $.each(Object.keys(list_to_replace), function(index, item) {
            var re = new RegExp(item, "g");
            $(domClone).html(function (index, html) {
                return html.replace(re, list_to_replace[item]);
            });
        });
        postRows.push($(domClone).html());
    });
    return postRows;
}
编辑:对此感到抱歉。这应该可行,但我会指出它返回克隆的文本,但它没有执行替换,因为它正在处理克隆。