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
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With