Cha*_*era 5 javascript regex template-engine object node.js
我目前正在为NodeJs制作一个小模块.我需要一点帮助.
我会这样说的.我有一个带字符串的变量.它包含一个字符串html值.现在我需要$(title)用我的对象替换这样的东西{ "title" : "my title" }.这可以扩展到用户提供的任何内容.这是当前的代码.我认为我需要RegEx才能做到这一点.你能帮助我吗?
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" });Run Code Online (Sandbox Code Playgroud)
您可以使用正则表达式使用简单的模板函数,
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;
}
Run Code Online (Sandbox Code Playgroud)
用得像
var result = replacer(html, { "title" : "my title", "text" : "text is this" });
Run Code Online (Sandbox Code Playgroud)
编辑
实际上,作为评论中提到的torazaburo,它可以被重构为
var replacer = function(tpl, data) {
return tpl.replace(/\$\(([^\)]+)?\)/g, function($1, $2) { return data[$2]; });
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助
小智 6
此解决方案使用模板字符串来完成您想要的一切。
该解决方案的优点是,与另一个答案中提出的基于 regexp 的幼稚模板替换策略相比,它支持任意计算,如
replacer("My name is ${name.toUpperCase()}", {name: "Bob"});
Run Code Online (Sandbox Code Playgroud)
在这个版本的 中replacer,我们new Function用来创建一个函数,该函数将对象属性作为参数,并返回作为模板字符串评估的传入模板。然后我们使用对象属性的值调用该函数。
function replacer(template, obj) {
var keys = Object.keys(obj);
var func = Function(...keys, "return `" + template + "`;");
return func(...keys.map(k => obj[k]));
}
Run Code Online (Sandbox Code Playgroud)
我们使用${}for 替换(而不是$())来定义模板,但会转义\${以防止评估。(我们也可以将其指定为常规字符串文字,但会失去多行功能)。
var html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document \${title}</title> <!-- escape $ -->
</head>
<body>
<h1>Test file, \${text}</h1> <!-- escape $ -->
</body>
</html>`;
Run Code Online (Sandbox Code Playgroud)
现在一切都如你所愿:
replacer(html, { "title" : "my title", "text" : "text is this" });
Run Code Online (Sandbox Code Playgroud)
简单的例子:
> replacer("My name is ${name}", {name: "Bob"})
< "My name is Bob"
Run Code Online (Sandbox Code Playgroud)
以下是计算字段的示例:
> replacer("My name is ${name.toUpperCase()}", {name: "Bob"})
< "My name is BOB"
Run Code Online (Sandbox Code Playgroud)
甚至
> replacer("My name is ${last ? lastName : firstName}",
{lastName: "Jones", firstName: "Bob", last: true})
< "My name is Jones"
Run Code Online (Sandbox Code Playgroud)