简体   繁体   English

JavaScript REGEX全部匹配并替换

[英]JavaScript REGEX Match all and replace

I am coding a simple templating function in javascript. 我正在用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 {{name}}将替换为javascript数组中加载的内容,例如

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. 好吧,首先,您需要在正则表达式上使用g标志。 This tells JavaScript to replace all matched values. 这告诉JavaScript替换所有匹配的值。 Also you can supply a function to the replace method. 您也可以为replace方法提供功能。 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/ http://jsfiddle.net/zDJLd/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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