Replace keys in template string with object properties

前端 未结 3 1144
南旧
南旧 2020-12-06 03:25

I have an object like this.

var obj = {Id:1,Rate:5,Price:200,Name:\"History\"}

And a template like this.

var templateString         


        
相关标签:
3条回答
  • 2020-12-06 03:56

    You can use replace with a callback :

    var optionString = templateString.replace(/{(\w+)}/g, function(_,k){
          return obj[k];
    });
    

    Demonstration

    0 讨论(0)
  • 2020-12-06 03:58

    Without using regex, this can be done by finding all the properties of the object using Object.keys and then replace each of them by it's value.

    Try like this:

    Object.keys(obj).forEach(key => {
      templateString = templateString.replace(`**${key}**`, `"${obj[key]}"`);
    });
    
    0 讨论(0)
  • 2020-12-06 04:16

    Just this will work for you if it has just one occurrence

    var optionString = templateString.replace('{Id}',obj.Id).replace('{Name}',obj.Name)
    
    0 讨论(0)
提交回复
热议问题