简体   繁体   中英

JavaScript REGEX Match all and replace

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.

an example of a template is:

{{name}} is {{age}}

These are dynamic, so ideally I want to use regex to match and replace the placeholders based on their names, eg

{{name}} is to be replaced by content loaded in a javascript array, eg

data.name

data.age

This is my regex: /\\{\\{(.*?)\\}\\}/

This is working fine, but after a lot of searching I can't find a defined way of iterating through every regex match.

Thanks in advance

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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM