Skip to content

Instantly share code, notes, and snippets.

@bitwalker
Created December 3, 2013 22:45
Show Gist options
  • Save bitwalker/7778962 to your computer and use it in GitHub Desktop.
Save bitwalker/7778962 to your computer and use it in GitHub Desktop.
Just in case I ever need to extract values from a string using a mask
/**
* Extracts values from a string using a pattern mask.
*
* Example:
* var greetFormat = 'Hello {{name}}! My name is {{greeter}}!'
* extract(greetFormat, 'Hello Paul! My name is Robotron!') => { name: 'Paul', greeter: 'Robotron'}
*/
function extract(format, s) {
var parser = getParser(format);
var parsed = parser.mask.exec(s);
if (!parsed) return {};
var result = {};
for (var i = 0; i < parser.tokens.length; i++) {
result[parser.tokens[i]] = parsed[i + 1];
}
return result;
}
function getParser(s) {
var re = /\{\{(\w*)\}\}/g;
var results;
var tokens = [];
var mask = s;
while ((results = re.exec(s)) !== null)
{
var token = results[1];
tokens.push(token);
var maskPattern = new RegExp("\{\{" + token + "\}\}");
mask = mask.replace(maskPattern, '(.*)');
}
return { mask: new RegExp(mask), tokens: tokens };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment