简体   繁体   English

简单的JavaScript字符串提取

[英]Simple javascript string extraction

I have such string: 我有这样的字符串:

"{{foo}} is {{bar}}"

I would like to extract values from {{}}, how I can achieve this? 我想从{{}}中提取值,如何实现呢? Expected result is 预期结果是

["foo", "bar"]

I tried 我试过了

"{{foo}} is {{bar}}".match(/\{\{(.*?)\}\}/g)

But its not working as I expected. 但是它没有按我预期的那样工作。

You should use exec in a loop like this to grab capturing groups with global flag in JS: 您应该在这样的循环中使用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"]

Regex is fine, just use map to strip the braces 正则表达式很好,只需使用map去掉括号

  var output = "{{foo}} is {{bar}}".match(/\\{\\{(.*?)\\}\\}/g).map(function(value){ return value.substring(2,value.length-2) }); document.body.innerHTML += output; 

In JS, match with g only returns top-level matches, no groups. 在JS中,与g match仅返回顶级匹配,不返回任何分组。 You can map the string as @gurvinder372 suggested: 您可以按照@ gurvinder372建议的方式映射字符串:

 res = "{{foo}} is {{bar}}".match(/{{.*?}}/g).map(s => s.slice(2, -2)); document.write('<pre>'+JSON.stringify(res,0,3)); 

or use .replace to populate the array: 或使用.replace填充数组:

 res = []; "{{foo}} is {{bar}}".replace(/{{(.*?)}}/g, (_, $1) => res.push($1)); document.write('<pre>'+JSON.stringify(res,0,3)); 

Note that there's no need to escape curly braces in your regex. 请注意,您无需在正则表达式中使用花括号。

Try this 尝试这个

 var arr = []; var str = "{{foo}} is {{bar}}" str.replace(/{{(.*?)}}/g, function(s, match) { arr.push(match); }); document.write('<pre>'+JSON.stringify(arr)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM