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" });
This solution uses template strings to do everything you want.
This solution has the advantage that, in contrast to the naive roll-your-own regexp-based template replacement strategy as proposed in another answer, it supports arbitrary calculations, as in
In this version of
replacer
, we usenew Function
to create a function which takes the object properties as parameters, and returns the template passed in evaluated as a template string. Then we invoke that function with the values of the object properties.We define the template using
${}
for substitutions (instead of$()
), but escaping as\${
to prevent evaluation. (We could also just specify it as a regular string literal, but would then lose multi-line capability).Now things work exactly as you want:
Simple example:
Here's an example of calculated fields:
or even
Since you are using ES6 template string you can use a feature called 'tagged template strings'. Using tagged template strings you are allowed to modify the output of a template string. You create tagged template string by putting a 'tag' in front of the template string, the 'tag' is a reference to a method that will receive the string parts in a list as the first argument and the interpolation values as remaining arguments. The MDN page on template strings already provides an example template string 'tag' that we can use:
You use the 'tag' by calling:
Notice that interpolation of variables uses the syntax
${'key'}
instead of$(key)
. You can now call the produced function to get the desired result:Run the code example on es6console
You can use a simple template function using regex,
use like
jsfiddle
detail here
EDIT
Actually as torazaburo mentioned in the comment, it can be refactored as
jsfiddle
hope this helps