0

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!

Alex
  • 34,699
  • 13
  • 75
  • 158

1 Answers1

2

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.

Jonathan Card
  • 122
  • 1
  • 8
  • Thanks, @JonathanCard. How does the `Object.Keys()` work? I've never seen that before. – Alex Jun 03 '15 at 22:14
  • 1
    It lists the keys in a hash table. The purpose of that line is to iterate of the items you wish to replace in a way that lets you look up what you want to replace it with. Got it from here: http://stackoverflow.com/questions/18912/how-to-find-keys-of-a-hash – Jonathan Card Jun 03 '15 at 22:23
  • please see update above @JonathanCard. The code in the answer doesn't work. It throws an error. – Alex Jun 04 '15 at 16:00
  • 1
    Oh, I'm sure the answer is inter redefinition of "this" in the way I changed the nesting. I'll edit when I get back from lunch. I'm afraid I just checked syntax, since I didn't have a good way to test. – Jonathan Card Jun 04 '15 at 16:06
  • One other correction: when pushing a new element into the array, the line needs to read... `postRows.push($(this).html());`, otherwise it will keep populating the array with the same data over and over again. – Alex Jun 05 '15 at 17:42