Tuesday, November 29, 2016

Simple way to embed html in javasript

If you are not working with React and JSX, this could be a quick way to embed html inside Javascript...

// Simple way to embed html in javasript
Array.prototype.joinHtml = function () {
return this.join('');
};
String.prototype.supplant = function (o) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};
var html = [
'<div class="{classes}">',
'<p>{text}</p>',
'</div>',
].joinHtml().supplant({
classes: "class1",
text: "dummy text"
});
console.log(html); // output: <div class="class1"><p>dummy text</p></div>

No comments :

Post a Comment