Created
October 3, 2011 20:04
-
-
Save lsauer/1260083 to your computer and use it in GitHub Desktop.
JavaScript compensating for RegExp global non capturing groups
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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