Created
September 22, 2015 16:25
-
-
Save logarytm/09da3b7ffc0bf7aebe3e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| /** | |
| * Regular expressions of the delimiters. | |
| * @type {Array<string>} | |
| */ | |
| var DELIMS = ['%', '%']; | |
| /** | |
| * Replaces all occurences of {<key>} with parameters[key]. When an | |
| * appropriate property of parameters is not found, omits the substitution. | |
| * | |
| * This function supports nested parameters (eg. weather.cloudy) | |
| * | |
| * @param {string} string - The source string | |
| * @param {Object} parameters - A dict of parameters | |
| * @return {string} | |
| */ | |
| function bindString(string, parameters) { | |
| var re = new RegExp(DELIMS[0] + '([a-z0-9_]+(?:\.[a-z0-9_]+)*)' + DELIMS[1], 'gi'); | |
| return string.replace(re, function(match, path) { | |
| path = path.split('.'); | |
| var replacement = parameters; | |
| while (path.length && replacement !== undefined) { | |
| replacement = replacement[path[0]]; | |
| path.shift(); | |
| } | |
| return (replacement === undefined ? match : replacement); | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment