用JavaScript对象替换字符串值

nszi6y05  于 4个月前  发布在  Java
关注(0)|答案(5)|浏览(60)

我目前正在为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" });

字符串

wztqucjr

wztqucjr1#

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

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

编辑

实际上,正如虎三郎在评论中提到的,它可以重构为

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


jsfiddle
希望这有帮助

xzlaal3s

xzlaal3s2#

这个解决方案使用template strings来做你想要的一切。
这种解决方案的优点是,与另一个答案中提出的简单的基于自滚regexp的模板替换策略相比,它支持任意计算,如

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"

4ktjp1zp

4ktjp1zp3#

因为你使用的是ES6模板字符串,所以你可以使用一个叫做'tagged template strings'的特性。使用带标签的模板字符串,你可以修改模板字符串的输出。你可以通过在模板字符串前面放一个“标签”来创建带标签的模板字符串,“标签”是对一个方法的引用,该方法将接收列表中的字符串部分作为第一个参数,并将插值作为剩余参数。关于模板字符串的MDN页面已经提供了一个我们可以用途:使用的示例模板字符串“tag”:

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('');
 });
}

字符串
您可以通过调用以下命令来使用'tag':

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上运行代码示例

e4eetjau

e4eetjau4#

我用的是原型,看起来更干净。

String.prototype.replaceByObject = function(obj) {
    return this.replace(RegExp(Object.keys(obj).join('|'), 'g'), function(val) {
        return obj[val];
    });
}

字符串
这样使用它

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

nzkunb0c

nzkunb0c5#

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

字符串
您可以通过调用以下命令来使用'tag':

<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'}

相关问题