问题描述
我在javascript中编写一个简单的模板函数。
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.
模板的一个例子是:
{{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}}将被javascript数组中加载的内容替换,例如
{{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.
提前致谢
推荐答案
嗯,首先你需要<$ c $正则表达式上有c> g 标志。这告诉JavaScript替换所有匹配的值。您还可以为替换
方法提供一个函数。这样的事情:
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.
这篇关于JavaScript REGEX匹配所有并替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!