syuichi-tsuji
1/15/2013 - 10:00 AM

String interpolation method for underscore.js.

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;
      }
    );
  }
});