我有这样的字符串:简单的JavaScript字符串提取
"{{foo}} is {{bar}}"
我想提取值{{}},我怎么能做到这一点? 预期的结果是
["foo", "bar"]
我试图
"{{foo}} is {{bar}}".match(/\{\{(.*?)\}\}/g)
但它不是如我所料工作。
我有这样的字符串:简单的JavaScript字符串提取
"{{foo}} is {{bar}}"
我想提取值{{}},我怎么能做到这一点? 预期的结果是
["foo", "bar"]
我试图
"{{foo}} is {{bar}}".match(/\{\{(.*?)\}\}/g)
但它不是如我所料工作。
您应该使用exec
在这样的循环抓住全球标志捕获组在JS:
var m;
var re = /\{\{(.*?)\}\}/g
var str = "{{foo}} is {{bar}}"
var matches = [];
while((m=re.exec(str)) != null) {
matches.push(m[1]);
}
console.log(matches);
//=> ["foo", "bar"]
这是发布的最佳解决方案 - 如果您使用的是正则表达式,请将其用于整个工作。不要因为没有得到正确的输出而退回到串扰。 –
@JamesThorpe它取决于。该解决方案在可读性方面失败。 – Lewis
@Tresdin不是真的 - 这是一个非常直接的实现,如何使用'.exec',并且不需要对找到的值进行后处理。 –
正则表达式是好的,只是用map
剥离括号
var output = "{{foo}} is {{bar}}".match(/\{\{(.*?)\}\}/g).map(function(value){ return value.substring(2,value.length-2) });
document.body.innerHTML += output;
试试这个
var arr = [];
var str = "{{foo}} is {{bar}}"
str.replace(/{{(.*?)}}/g, function(s, match) {
arr.push(match);
});
document.write('<pre>'+JSON.stringify(arr));
这是某种类型的模板吗?你打算用什么替换它们吗? – georg
@georg它来自模板,我正在做非常简单的原型,我只需要从模板中提取所有变量。 –