2014-04-03 39 views
0

http://codepen.io/anon/pen/eABbj/?editors=101JavaScript REGEX:如何从字符串中提取某些匹配项?

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 %>"] 

如何得到它?

回答

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 
}); 
相关问题