JavaScript REGEX Match all and replace

前端 未结 2 1092
情深已故
情深已故 2020-12-10 05:38

I am coding a simple templating function in javascript.

I have my template loading fine, now is the part when I need to parse the content to the placeholders.

<
相关标签:
2条回答
  • 2020-12-10 06:10
    var data = {
        name: 'zerkms',
        age: 42
    };
    
    var str = '{{name}} is {{age}}'.replace(/\{\{(.*?)\}\}/g, function(i, match) {
        return data[match];
    });
    
    console.log(str);
    

    http://jsfiddle.net/zDJLd/

    0 讨论(0)
  • 2020-12-10 06:25

    Well, first you'll need the g flag on the regex. This tells JavaScript to replace all matched values. Also you can supply a function to the replace method. Something like this:

    var result = str.replace(/\{\{(.*?)\}\}/g, function(match, token) {
        return data[token];
    });
    

    The second parameter matches the first subgroup and so on.

    0 讨论(0)
提交回复
热议问题