0

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.

1 Answer 1

1

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);

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

1 Comment

Thanks for this, haven't come across Template Literals before, will give it a go.

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.