Skip to content

Instantly share code, notes, and snippets.

@logarytm
Created September 22, 2015 16:25
Show Gist options
  • Select an option

  • Save logarytm/09da3b7ffc0bf7aebe3e to your computer and use it in GitHub Desktop.

Select an option

Save logarytm/09da3b7ffc0bf7aebe3e to your computer and use it in GitHub Desktop.
/**
* 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