Reputation: 12936
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?
Upvotes: 0
Views: 738
Reputation: 24472
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)
Upvotes: 3
Reputation: 561
The first thing i see is that you're not escaping your backslashes.
var expression = new RegExp("\\[sub:" + item.Key + "\\]", "g");
Upvotes: 0