Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for mustache-style double braces?

I'm using Mustache-style tags inside of AngularJS. What's the best regex to use to return an array of just the text inside the mustache braces?

Sample data:

"This could {{be }} a {{ string.with.dots_and_underscores }} of {{ mustache_style}} words which {{could}} be pulled." 

Expected output:

['be','string.with.dots_and_underscores','mustache_style','could'] 
like image 229
RandallB Avatar asked Mar 19 '13 14:03

RandallB


2 Answers

If you use a global search with .match, JavaScript won't give the capture groups in its array output. As such, you need to do it twice: Once to find the {{...}} pairs, then again to extract the names from within them:

str.match(/{{\s*[\w\.]+\s*}}/g)    .map(function(x) { return x.match(/[\w\.]+/)[0]; }); 
like image 150
Xophmeister Avatar answered Oct 11 '22 01:10

Xophmeister


Mod of Douglas Crockford's String.prototype.supplant

This will interpolate any {param} you have between handleBars ({}). I know this answer is somewhat extensive, but I assumed the question was probably regarding interpolation -- either way, I'd advise the reader to study the regex, regardless.

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); 

Hope this helps

like image 32
Cody Avatar answered Oct 11 '22 01:10

Cody