我在AngularJS中使用了Mustache风格的标签。最好的正则表达式是什么,用来返回一个只包含大括号内文本的数组?
示例数据:
"This could {{be }} a {{ string.with.dots_and_underscores }} of {{ mustache_style}} words which {{could}} be pulled."
预期输出:
['be','string.with.dots_and_underscores','mustache_style','could']
发布于 2013-03-19 22:56:46
如果将全局搜索与.match
一起使用,JavaScript将不会在其数组输出中提供捕获组。因此,您需要执行两次操作:一次是查找{{...}}
对,第二次是从其中提取名称:
str.match(/{{\s*[\w\.]+\s*}}/g)
.map(function(x) { return x.match(/[\w\.]+/)[0]; });
发布于 2015-08-06 01:53:11
道格拉斯·克罗克福德的String.prototype.supplant
模型
这将对handleBars ({}
)之间的任何{param}
进行插值。我知道这个答案有点广泛,但我认为这个问题可能是关于插值的--不管怎样,我都建议读者研究正则表达式。
clear();
function interpolate(str) {
return function interpolate(o) {
return str.replace(/{([^{}]*)}/g, function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
});
}
}
var terped = interpolate('The {speed} {color} fox jumped over the lazy {mammal}')({
speed: 'quick',
color: 'brown',
mammal: 'dog'
});
console.log(terped);
希望这能有所帮助
发布于 2013-03-19 23:00:23
您可以尝试使用exec()
来执行此操作:
var list = [],
x = '"This could {{be }} a {{ string }} of {{ mustache_style}} words which {{could}} be pulled."',
re = /{{\s*([^}]+)\s*}}/g,
item;
while (item = re.exec(x))
list.push(item[1]);
https://stackoverflow.com/questions/15502629
复制相似问题