1

I am attempting to replace some custom variable tags in a content block with values from an array. I currently have some working code that is successfully replacing variables that look like %([variable_name])% however, I need it to replace variables that look like <%[variable_name]%>. I have been messing around with the following code for a few hours, and I'm having trouble wrapping my head around the regex portions, and getting it to work correctly with my new variable format.

Here is the code that currently works for %([variable_name])%, how can I get it to work for <%[variable_name]%>?

$.each(data, function(key, value){
    var our_key = "%(["+key+"])%";
    our_key = our_key.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
    var regex = new RegExp(our_key, 'g');
    new_contents = new_contents.replace(regex,value);
});

Edit: The real problem was that I was grabbing my "new_contents" using the jquery '.html()' attribute, which was replacing my '<' and '>' with '& lt;' and '& gt;'

2 Answers 2

1

Why not the other way round?

var replacementMap = {
        "name": "John Doe"
    },
    text = "Hello <%[name]%>!";

text = text.replace(/<%\[([^\]]+)\]%>/g, function(match, key) {
    return replacementMap[key] || match;
});

console.log(text);    // "Hello John Doe!"

fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! The problem turned out to be a number of things, but this was a much better solution.
1

Try replacing "%(["+key+"])%" with "<%["+key+"]%>":

$.each(data, function(key, value){
    var our_key = "<%["+key+"]%>";
    our_key = our_key.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
    var regex = new RegExp(our_key, 'g');
    new_contents = new_contents.replace(regex,value);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.