javascriptregexnode.jsobjecttemplate-engine

Replace string value with javascript object


I am currently making a small module for NodeJs. For which I need a small help.

I will tell it like this. I have a variable with string. It contains a string html value. Now I need to replace $(title) something like this with my object { "title" : "my title" }. This can be expanded to anything with user provide. This is current code.I think that I need RegEx for do this. Can you guys help me with this?

var html = `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document $(title)</title>
</head>
<body>

  <h1>Test file, $(text)</h1>

</body>
</html>`;

function replacer(html, replace) {
  // i need a regex to replace these data
  //return replacedData;
}

replacer(html, { "title" : "my title", "text" : "text is this" });


Solution

  • You can use a simple template function using regex,

    var replacer = function(tpl, data) {
      var re = /\$\(([^\)]+)?\)/g, match;
      while(match = re.exec(tpl)) {
        tpl = tpl.replace(match[0], data[match[1]])
        re.lastIndex = 0;
      }
      return tpl;
    }
    

    use like

    var result = replacer(html, { "title" : "my title", "text" : "text is this" });
    

    jsfiddle

    detail here

    EDIT

    Actually as torazaburo mentioned in the comment, it can be refactored as

    var replacer = function(tpl, data) {
        return tpl.replace(/\$\(([^\)]+)?\)/g, function($1, $2) { return data[$2]; });
    }
    

    jsfiddle

    hope this helps