You can use RegEx.
str.replace(/{[^{}]+}/g, m => tags[m] || m);
The function m => tags[m] || m is using ES6 arrow function syntax.
Equivalent code in ES5:
function(m) {
return tags[m] || m;
}
If the matched string(tag) is found in the object, then the value of that tag is returned. If not then the matched string itself is returned.
RegEx Explanation:
{: Match { literal
[^{}]+: Match one or more characters except { and }
}: Match } literal
g: Global flag
var str = 'Hello {tag1}, I\'m {tag2}. Where is {tag3}. - {tag1} {NoTag}';
var tags = {
"{tag1}": "one",
"{tag2}": "two",
"{tag3}": "three"
};
str = str.replace(/{[^{}]+}/g, m => tags[m] || m);
console.log(str);
document.body.innerHTML = str;
I'll also suggest to use ES6 template literals.
var tag1 = 'one',
tag2 = 'two',
tag3 = 'three';
var str = `Hello ${tag1}, I\'m ${tag2}. Where is ${tag3}.`;
var tag1 = 'one',
tag2 = 'two',
tag3 = 'three';
var str = `Hello ${tag1}, I\'m ${tag2}. Where is ${tag3}.`;
document.body.innerHTML = str;