Skip to content

Instantly share code, notes, and snippets.

@supasympa
Created July 2, 2013 14:34
Show Gist options
  • Save supasympa/5909808 to your computer and use it in GitHub Desktop.
Save supasympa/5909808 to your computer and use it in GitHub Desktop.
A simple string format function replacing items in a string with their respective strings / numbers in a map.
define([],
function () {
var resolvePath = function (path, map) {
var pathParts, i, ctx;
ctx = map;
i = 0;
pathParts = path.split('.');
for (; i < pathParts.length; i++) {
if(!ctx[pathParts[i]]){
throw new Error('cannot resolve part of path'+ JSON.stringify(ctx) +' > '+ path);
}
ctx = ctx[pathParts[i]];
}
return ctx;
}
var format = function (inStr, replacements) {
if(!inStr){
throw new Error('String format > No string format (inStr) provided.');
}
if(!replacements){
throw new Error('String format > No replacements provided.');
}
var i, path,
matches = inStr.match(/{{[0-9|a-z|A-Z|/./-/$]*}}/igm);
for (i = 0; i < matches.length; i++) {
path = '';
path = matches[i].replace('{{', '').replace('}}', '');
inStr = inStr.replace(matches[i], resolvePath(path, replacements));
}
return inStr;
};
return format;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment