Reputation: 173
In an angular controller I have:
var stringTemplate = "{{data.a}} - {{data.b}}";
var data = {a: "example1", b: "example2"};
Is there a way to replace the expressions in stringTemplate
with static values from data
. So in this case the result should be "example1 - example2"
.
I need to store this in a database and use later when data
is not available.
Values in data
and stringTemplate
will change.
Upvotes: 0
Views: 120
Reputation: 87203
You can use Template Literals syntax introduced in ES6.
var data = {
a: "example1",
b: "example2"
};
var stringTemplate = `${data.a} - ${data.b}`;
console.log(stringTemplate);
ES5: Using Regex
var data = {
a: "example1",
b: "example2"
};
var stringTemplate = "{{data.a}} - {{data.b}}";
stringTemplate = stringTemplate.replace(/\{{(.*?)}}/g, function($0, $1) {
return data[$1.split('.')[1]] || $0;
});
console.log(stringTemplate);
Upvotes: 1