【问题标题】:Replace string value with javascript object用 javascript 对象替换字符串值
【发布时间】:2016-04-15 23:20:03
【问题描述】:

我目前正在为 NodeJs 制作一个小模块。为此我需要一点帮助。

我会这样说。 我有一个带字符串的变量。它包含一个字符串 html 值。现在我需要用我的对象{ "title" : "my title" } 替换类似这样的$(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" });

【问题讨论】:

  • 由于您使用的是节点,因此请使用许多强大的模板引擎之一,例如 ejs。

标签: javascript regex node.js object template-engine


【解决方案1】:

由于您使用的是 ES6 模板字符串,因此您可以使用名为 'tagged template strings' 的功能。使用标记的模板字符串,您可以修改模板字符串的输出。您可以通过在模板字符串前面放置一个“标签”来创建标记模板字符串,“标签”是对一个方法的引用,该方法将接收列表中的字符串部分作为第一个参数,并将插值值作为其余参数。模板字符串上的 MDN 页面已经提供了一个我们可以使用的示例模板字符串“标签”:

function template(strings, ...keys) {
  return (function(...values) {
    var dict = values[values.length - 1] || {};
    var result = [strings[0]];
    keys.forEach(function(key, i) {
      var value = Number.isInteger(key) ? values[key] : dict[key];
      result.push(value, strings[i + 1]);
    });
    return result.join('');
 });
}

您通过调用来使用“标签”:

var tagged = template`<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
  <title>Document ${'title'}</title>
</head>
<body>

  <h1>Test file, ${'text'}</h1>

</body>
</html>`;

请注意,变量插值使用语法${'key'} 而不是$(key)。您现在可以调用生成的函数来获得所需的结果:

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

在es6console上运行代码示例

【讨论】:

  • 我使用 NodeJs Streams 来读取 html 文件。我可以用它吗?
  • NodeJS 5.0 和 4.0 支持模板字符串(当您使用 --harmony 启动节点时),但您不能将输入流转换为模板字符串。它们必须由`ticks构建
  • 我认为模板字符串不需要--harmony 标志。
【解决方案2】:

您可以使用正则表达式来使用简单的模板函数,

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" });

jsfiddle

detail here

编辑

其实正如评论中所说的torazaburo,可以重构为

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

jsfiddle

希望对你有帮助

【讨论】:

  • 嗯,当然,但这不适用于$(title.toUpperCase())。
  • 你可以跳过循环,直接说return tpl.replace(/\$\(([^\)]+)?\)/g, function(_, match) { return data[match]; });。
  • @torazaburo,OP 没有要求复杂的替换器,大多数时候需要简单的替换器。没错,所以我重构了替换功能
  • 我刚刚在 Chrome 的控制台中尝试过,它没有替换我字符串中的任何内容。
【解决方案3】:

这个解决方案使用template strings 来做你想做的一切。

该解决方案的优势在于,与另一个答案中提出的基于滚动你自己的基于正则表达式的模板替换策略相比,它支持任意计算,如

replacer("My name is ${name.toUpperCase()}", {name: "Bob"});

在这个版本的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]));
}

我们使用${} 定义模板进行替换(而不是$()),但转义为\${ 以防止评估。 (我们也可以将其指定为常规字符串文字,但随后会失去多行功能。

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>`;

现在一切如你所愿:

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

简单示例:

> replacer("My name is ${name}", {name: "Bob"})
< "My name is Bob"

以下是计算字段的示例:

> replacer("My name is ${name.toUpperCase()}", {name: "Bob"})
< "My name is BOB"

甚至

> replacer("My name is ${last ? lastName : firstName}", 
    {lastName: "Jones", firstName: "Bob", last: true})
< "My name is Jones"

【讨论】:

  • 当模板字符串引用“obj”中不存在的键时,有什么方法可以让替换器工作?
【解决方案4】:
var binddingData=function(id,data){
    var me=this,
        arr=[];
    arr=getControlBindding(id);
    arr.forEach(function(node){
        var content=getBinddingContent(node.getAttribute('DataTemp'),data);
        binddingToHtml(node,content);
    })

}
var getControlBindding=function(id){
    var me=this;
    return document.querySelectorAll('[DataTemp]');
}


var getBinddingContent=function(temp,data){
    var me=this,
        res='',
        hasNull=false;
    if(temp==null||typeof temp=='undefined'){
            return res;
        }
    res= temp.replace(/\$\{([^\}]+)?\}/g, function($1, $2) { 
        if(data[$2]==null||typeof data[$2]=='undefined'){
            hasNull=true;
        }
        return data[$2]; 
    });
    return hasNull?'':res;

}

var binddingToHtml=function(node,content){
    var me=this;
    if(node.getAttribute('IsDateTime')){
        node.innerText='';//if u want change it to datetime string
        return;
    }
    if(node.getAttribute('AddBr') && content==''){
        node.innerText='';
        var brTag=document.createElement('br');
        node.appendChild(brTag);
        return;
    }
   node.innerText=content;
}

您通过调用来使用“标签”:

<div DataTemp="${d1}"></div> 
    <div DataTemp="${d2}"></div>
    <div DataTemp="${d3}"></div> 
    <div DataTemp="${d3}+ +${d1}"></div> 
    <div DataTemp="${d3}/${d1}"></div>     
    <div DataTemp="${d4}\${d1}"></div>     
    <div DataTemp="(${d5}\${d1})"></div> 
    <div DataTemp="(${d3}\${d1})"></div>

有数据var data={d1:'t1',d2:'t2',d3:'t3'}

【讨论】:

  • 欢迎来到 SO。为了让您的回答有帮助,请先给出描述,然后发布您的代码以解决问题。
猜你喜欢
  • 2014-06-30
  • 2020-04-15
  • 2022-06-15
  • 1970-01-01
  • 2016-07-07
  • 2020-01-13
  • 1970-01-01
  • 1970-01-01
  • 2023-01-28
相关资源
最近更新 更多