Created
July 2, 2013 14:34
-
-
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.
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
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