views:

199

answers:

3

I have an array of objects that have 2 properties: Key and Value. I have a block of text with placeholders that correspond to the object Keys. I want to replace the placeholders with the corresponding Value from the object with the matching key.

I have the following code:

function LoadReplacementData(replacementData)
{
    var text = $("#textblock").html();

    $.each(replacementData, function(index, item)
    {
        var expression = new RegExp("\[sub:" + item.Key + "\]", "g");
        text = text.replace(expression, item.Value);
    });

    $("#textblock").html(text);
}

I have tested the pattern over at RegExLib.com under JavaScript and it comes back with all instances of the placeholders which are in the form of "[sub:KeyText]". I have also ensured the Keys and Values are coming back properly. I have also looped through the various expressions that are generated and the resulting patterns are accurate.

The above code results in an "Out of Memory Exception" at the line of text = text... If I remove the assignment, nothing happens.

Any idea where I'm going wrong to do this replacement?

A: 

Why regular expression and not simple replace in this case?

EFraim
I think replace will only replace one instance, not all.
SolutionYogi
A: 

The first thing i see is that you're not escaping your backslashes.

var expression = new RegExp("\\[sub:" + item.Key + "\\]", "g");
AcousticBoom
@EFraim True but it is still a JavaScript string and needs to be escaped prior to being converted into a pattern.
JamesEggers
After I escaped the back slashes in the string so that the pattern would see it as a single backslash, it resolved the issue.
JamesEggers
And you propose using a regex for single replace all?
EFraim
+3  A: 

What about using join and split to prevent memory errors? It will significantly save on memory overhead as it doesn't have to parse the entire string multiple times using a regular expression, just a standard string method.

text = text.split("[sub:"+item.Key+"]").join(item.Value)
tj111