Last active
September 27, 2022 22:55
-
-
Save josdejong/4537647 to your computer and use it in GitHub Desktop.
String interpolation method for underscore.js.
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
/* | |
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