Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, e.g.

{{name}} is to be replaced by content loaded in a javascript array, e.g.

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

like image 763
André Figueira Avatar asked Jun 12 '13 00:06

André Figueira


People also ask

Is there a Replace All in JavaScript?

replaceAll() The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match.

Can I use regex in replace?

The Regex. Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match if any of the following conditions is true: If the replacement string cannot readily be specified by a regular expression replacement pattern.


2 Answers

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.

like image 158
rossipedia Avatar answered Oct 19 '22 13:10

rossipedia


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/

like image 41
zerkms Avatar answered Oct 19 '22 13:10

zerkms