用javascript对象替换字符串值 [英] Replace string value with javascript object
问题描述
我目前正在为NodeJ制作一个小模块.为此,我需要一点帮助.
I am currently making a small module for NodeJs. For which I need a small help.
我会这样说.我有一个带字符串的变量.它包含一个字符串html值.现在,我需要将 $(title)
替换为我的对象 {"title":"my title"}
.可以通过用户提供的内容扩展为任何内容.这是当前代码.我想我需要RegEx来做到这一点.你们可以帮我吗?
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" });
推荐答案
您可以使用正则表达式使用简单的模板函数,
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;
}
使用方式
var result = replacer(html, { "title" : "my title", "text" : "text is this" });
编辑
实际上就像评论中提到的torazaburo一样,它可以重构为
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]; });
}
希望这会有所帮助
这篇关于用javascript对象替换字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!