JavaScript REGEX:如何从字符串中提取某些匹配项?

时间:2014-04-03 16:53:44

标签: javascript regex

http://codepen.io/anon/pen/eABbj/?editors=101

HTML:

<script type="text/template" id="tpl-person">
  <%= name %> is <%= age %> years old. He works as a <%= occupation %>.  
</script>

JS:

String.prototype.template = function(data) {
    var tags = this.match(/\<%=(.+?)%\>/);
    console.log(tags);
};

document.getElementById('tpl-person').innerHTML.template({
    name: 'TK',
    age: 25,
    occupation: 'Web Developer'
});

上面的控制台日志是:

输出是:

["<%= name %>", " name ", index: 3, input: "↵  <%= name %> is <%= age %> years old. He works as a <%= occupation %>."]

我需要它只是:

["<%= name %>", "<%= age %>", "<%= occupation %>"]

如何获得这个?

1 个答案:

答案 0 :(得分:3)

使用g修饰符:/<%=(.+?)%>/g

这将为您提供一系列匹配,而不是第一个匹配及其子模式。

编辑:那就是说,你可能会想要一个替换:

return this.replace(/<%=\s*(.+?)\s*%>/g,function(_,key) {
    return data[key] || "##"+key+"##";
    // that || and the bit after it offer a fallback so you can see failed tags
});