JavaScript REGEX Match everything and replace

I am coding a simple template function in javascript.

I have a great template loading, now this is the part when I need to parse the contents for placeholders.

template example:

{{name}} is {{age}} 

They are dynamic, so ideally I want to use a regular expression to match and replace placeholders based on their names, for example.

{{name}} should be replaced by content loaded into a javascript array, for example.

 data.name data.age 

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

This works fine, but after a lot of searching, I cannot find a specific way to repeat each regular expression match.

Thank you in advance

+6
source share
2 answers

Well, first you need the g flag in the regular expression. This tells JavaScript to replace all matched values. You can also provide a function to the replace method. Something like that:

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

The second parameter corresponds to the first subgroup, etc.

+17
source
 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/

+4
source

Source: https://habr.com/ru/post/947063/


All Articles