使用来自JSON对象的占位符值替换字符串

时间:2016-04-15 20:56:10

标签: javascript json

我有一个字符串“Good $ timeOfTheDay $,$ name $”

$ timeOfTheDay $和$ name $是占位符,其值包含在JSON对象中。

var content = { "timeOfTheDay" : "evening",
                "name" : "Jack",  
                "city" : "New York",  
                "age" : "25",  
              }

想要使用JSON对象中的值替换字符串中的占位符。结果字符串将是:“晚上好,杰克”

想在javascript中执行此操作。这不涉及与DOM的任何交互。

我猜测蛮力的方式是通过编写JS代码来进行替换,但是有没有库或其他方法来做到这一点?

欣赏任何想法/帮助。谢谢!

5 个答案:

答案 0 :(得分:2)

使用String.splitString.replaceArray.mapArray.join函数的扩展解决方案:

var content = {"timeOfTheDay" : "evening", "name" : "Jack", "city" : "New York", "age" : "25"},
    str = "Good $timeOfTheDay$, $name$", replaced = "";

var parts = str.split(/(\$\w+?\$)/g).map(function(v) {
    replaced = v.replace(/\$/g,"");
    return content[replaced] || replaced; 
});

console.log(parts.join(""));  // "Good evening, Jack"

附加示例:

...
str = "$name$ lives in $city$. He is $age$";
...
console.log(parts.join(""));  // "Jack lives in New York. He is 25"

答案 1 :(得分:0)

只需使用String.prototype.replace功能

即可



var content = { "timeOfTheDay": "evening", "name": "Jack", "city": "New York", "age": "25", }

var str = "Good $timeOfTheDay$, $name$"

var result = str.replace('$timeOfTheDay$', content.timeOfTheDay)
                .replace('$name$', content.name);

document.write(result);




答案 2 :(得分:0)



var content = { "timeOfTheDay" : "evening",
                "name" : "Jack",  
                "city" : "New York",  
                "age" : "25",  
              }
              
document.getElementById('greeting').placeholder = 'Good ' + content.timeOfTheDay + ', ' +content.name;

<input id='greeting'>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

此库可用于替换占位符。这也可以用于递归替换占位符。 https://github.com/tarangkhandelwal/substitutor.js

例如:

  

nameJson = {           “第一”:“约翰”,           “最后一个”:“李四”           }

     

var fullName = substitutor('我的名字是{first} {last}',nameJson);

答案 4 :(得分:0)

如果您想使用${var}惯例:

var content = {
  timeOfTheDay: 'evening',
  name: 'Jack',
  city: 'New York',
  age: '25'
};

var str = 'Good ${timeOfTheDay}, ${name}. I am from ${city}, ${age} years old';

var parts = str.split(/(\$\{\w+?})/g).map(function(v) {
  var replaced = v.replace(/\$\{(\w+?)}/g, '$1');
  return content[replaced] || v;
});

console.log(parts.join(''));

输出

Good evening, Jack. I am from New York, 25 years old