Skip to content

Instantly share code, notes, and snippets.

@josdejong
Last active September 27, 2022 22:55
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josdejong/4537647 to your computer and use it in GitHub Desktop.
Save josdejong/4537647 to your computer and use it in GitHub Desktop.
String interpolation method for underscore.js.
/*
String interpolation method for underscore.js
Usage:
var props = {
first: 'Jos',
last: 'de Jong'
};
var message = _.interpolate('Hello $first $last, welcome!', props);
var date = new Date();
var props = {
user: {
first: 'Jos',
last: 'de Jong'
},
time: {
date: date.getDate(),
month: date.getMonth(),
year: date.getFullYear()
}
};
var message = _.interpolate('Hello $user.first $user.last, ' +
'today is $time.year-$time.month-$time.date.', props);
See also:
http://underscorejs.org/
https://github.com/documentcloud/underscore/issues/939
*/
_.mixin({
/**
* Substitute properties in a string with their value.
* Properties start with a dollar sign, and can contain nested properties,
* by separating properties by a dot. In that case the provided object
* Variables without matching value will be left untouched.
*
* Example:
* var msg = _.interpolate('Hello, $name!', {name: 'Jos'});
*
* @param {String} str String containing properties.
* @param {Object} props Object with property values to be replaced.
* @return {String} interpolatedStr
*/
interpolate: function (str, props) {
return str.replace(/\$([\w\.]+)/g, function (original, key) {
var keys = key.split('.');
var value = props[keys.shift()];
while (keys.length && value != undefined) {
var k = keys.shift();
value = k ? value[k] : value + '.';
}
return value != undefined ? value : original;
}
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment