Skip to content

Instantly share code, notes, and snippets.

@lsauer
Created October 3, 2011 20:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lsauer/1260083 to your computer and use it in GitHub Desktop.
Save lsauer/1260083 to your computer and use it in GitHub Desktop.
JavaScript compensating for RegExp global non capturing groups
//author: lo sauer 2011
//given for instance, is a text with placeholders of which only the value is to be captured
//JS's 'match' ignores the non-capture group (?:...), for instance in a global search
str = "Hello I am {{name}}. Is it already the {{date}}";
str.match(/(?:\{{2})([a-z0-9]*)(?:\}{2})/i);
>>>["{{name}}", "name"]
str.match(/(?:\{{2})([a-z0-9]*)(?:\}{2})/gi);
>>>["{{name}}", "{{date}}"]
str.match(/\{{2}([a-z0-9]*)\}{2}/gi);
>>>["{{name}}", "{{date}}"]
//two solutions
//1.solution (for phptrim see here https://gist.github.com/1260006 )
str.match(/\{{2}([a-z0-9]*)\}{2}/gi).map(function(e){return e.phptrim('{}'); });
>>>["name", "date"]
//2.solution
var rexp = /\{{2}([a-z0-9]*)\}{2}/gi;
var matches = [];
while (m = rexp .exec(str))
{
matches.push(m[m.length-1]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment