You can use format unicorn to do this like stackExchange does, example:
Your Html:
<div id="messageLoader">
</div>
<script type="text/template" id="templateMessage">
<h2>{title}</h2>
<p>{message}</p>
<br>
<span><Strong>{sign}</strong><span>
</script>
Your script:
String.prototype.formatUnicorn = function () {
"use strict";
var str = this.toString();
if (arguments.length) {
var t = typeof arguments[0];
var key;
var args = ("string" === t || "number" === t) ?
Array.prototype.slice.call(arguments)
: arguments[0];
for (key in args) {
str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
}
}
return str;
};
var jsonMessage = {title:"Custom Template With Form Unicorn",message:"Stack Overflow Rocks bae !!",sign:"Stan Chacon"};
let myFirstUnicornTemplate = document.getElementById("templateMessage").text;
var template = myFirstUnicornTemplate.formatUnicorn(jsonMessage);
document.getElementById("messageLoader").innerHTML = template;
EDIT: fun fact you can use it here in stack overflow just copy and paste this on console :
"Hello {name}, welcome to StackOverflow {emoji}".formatUnicorn({name:"User",emoji:"=)"});
Or try the snippet:
String.prototype.formatUnicorn = function () {
"use strict";
var str = this.toString();
if (arguments.length) {
var t = typeof arguments[0];
var key;
var args = ("string" === t || "number" === t) ?
Array.prototype.slice.call(arguments)
: arguments[0];
for (key in args) {
str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
}
}
return str;
};
var x = "Hello {name}, welcome to StackOverflow {emoji}".formatUnicorn({name:"User",emoji:"=)"});
console.log(x);
Hope it helps =)