0

I have a javascript template were I want to replace a set value in multiple locations throughout the template, however in my current code only the first instance of the value placeholder is changing.

How do I replace all {{color}} placeholders with the same value?

My template:

<script type="text/template" id="styleTemplate">    
.item {
    color: {{color}};
    border-color:{{color}};
}
</script>

My JS:

var thisColor = "#000";
var template = $("#styleTemplate").html();
$('#styleTarget').html(template.replace("{{color}}",thisColor));

The result:

.item {
    color: #000;
    border-color:{{color}};
}

2 Answers 2

1

Akamaozu is really too lazy to make his code valid. A regular expression must be included in slashes, not backslashes. A backslash is needed inside a regex when you have to escape a character that otherwise has a special meaning or to create a metacharacter with a special meaning. So when you change your code to this it will work:

var thisColor = "#000",
    search = /{{color}}/g,
    template = $("#styleTemplate").html();

$('#styleTarget').html(template.replace(search, thisColor));

DEMO.

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

1 Comment

zing. I can't even explain why I thought back slash made sense, even after I posted the link to a regexp validator. 7 am is not my prime time, it seems.
0

Replace:

$('#styleTarget').html(template.replace("{{color}}",thisColor));

With:

$('#styleTarget').html(template.replace(\{{color}}\g,thisColor));

String.prototype.replace will replace only the FIRST match. What I've done is replaced the search string with a regular expression that will search for all instances of said search string.

Cheers!

3 Comments

Thanks Akamaozu, I tried your solution but unfortunately it didn't work. See JSfiddle here: jsfiddle.net/2uu6f1v1
I replaced the faulty regex I used (didn't remove your quotes around the regex) but jsfiddle still kept giving me issues with it, so .. regex101.com/r/pI3nY3/1
@AdamWilson Also, if you run jshint on the jsfiddle sample, you'll see it freak out over the regexp even though it's totally valid and does work. i'd put the code on my server but i'm really lazy atm. If you aren't able to confirm this when I'm less lazy, I will

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.