Alex
Alex

Reputation: 35831

Search and replace in an $.each()

I have the code below that loops over a section of the DOM, searches for 3 different strings, and replaces each with something else. I need to make it so that an arbitrary number of items can be searched for and replaced, instead of just 3. Is that possible with 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;
}

Update 1: The code in @JonathanCard's answer throws this error:

Cannot read property 'replace' of undefined

Please see this jsFiddle: http://jsfiddle.net/jsFiddlePlayer/vhg7csb7/12/

Update 2: The code in the answer works!

Upvotes: 0

Views: 53

Answers (1)

Jonathan Card
Jonathan Card

Reputation: 144

Try this:

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;
}

EDIT: Sorry about the confusion. This should work, but I will point out that it returns the text for a clone, but it doesn't perform the replacement since it is working on a clone.

Upvotes: 2

Related Questions