2014-04-03 118 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 
}); 
相關問題