0

I am trying to use replace() to parse template variables with dynamic content. However, the replace does not seem to work when I use $.each() to iterate through an array of replacements. Nothing is replaced. Here's my code:

         var defaults = {
                sample_div : '#sample-ref',
                remove_button : '#removereference',
                update_div : '#references',
                add_button : '#addReference',
                hidden_input : 'input[name="references"]'
            }; 


                    var options = $.extend(defaults, options);
                    var new_ref = $('[name="reference"]').val();
                    var existing = $(options.hidden_input).val();
                    if(new_ref.length > 0){
                        existing = existing.split(',');
                        existing.push(new_ref);
                        var sample = $(options.sample_div).html();
                        var replacements = {
                            ref_int : existing.length,
                            ref_url : new_ref
                        }
                        $.each(replacements, function(index, value){
                            sample = sample.replace(/{index}/g, value);                     
                        });
                        $(options.update_div).append(sample);
                    }

Here is more detailed code at jsFiddle. The problem occurs at line 25.

ShoeLace1291
  • 4,117
  • 11
  • 41
  • 65
  • possible duplicate of [How do you pass a variable to a Regular Expression JavaScript?](http://stackoverflow.com/questions/494035/how-do-you-pass-a-variable-to-a-regular-expression-javascript) –  Nov 05 '14 at 22:09

1 Answers1

0

After a bit of googling, I found this StackOverflow question. I came up with the following, which works.

sample = sample.replace(new RegExp("{"+index+"}", 'g'), value);

Community
  • 1
  • 1
ShoeLace1291
  • 4,117
  • 11
  • 41
  • 65