Skip to content

Instantly share code, notes, and snippets.

@inodb
Forked from poxip/string-format.js
Created February 25, 2016 23:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inodb/d803600ba1b2068d6021 to your computer and use it in GitHub Desktop.
Save inodb/d803600ba1b2068d6021 to your computer and use it in GitHub Desktop.
Python-like string format in JavaScript
/**
* Python-like string format function
* @param {String} str - Template string.
* @param {Object} data - Data to insert strings from.
* @returns {String}
*/
var format = function(str, data) {
var re = /{([^{}]+)}/g;
return str.replace(/{([^{}]+)}/g, function(match, val) {
var prop = data;
val.split('.').forEach(function(key) {
prop = prop[key];
});
return prop;
});
};
/**
* Python-like format method
* @param {Object} data - Data to insert strings from.
* @returns {String}
*/
String.prototype.format = function(data) {
return format(this, data);
};
var data = {
'result': '2-1',
'team a': {
name: 'Manchester United',
best: 'Ryan Giggs'
},
'team b': {
name: 'Chelsea',
best: 'Frank Lampard'
}
};
var r = format(
'{team a.name} won {result} against {team b.name},\n' +
'Best players: {team a.best}, {team b.best}',
data
);
console.log(r);
r = format(
'US Open Final: {0} vs {1}', [
'New York Red Bulls', 'Los Angeles Galaxy'
]
);
console.log(r);
r = '{team a}\'s {player} scored a goal against {team b}'.format({
'team a': 'Manchester United',
'team b': 'Arsenal',
'player': 'Wayne Rooney'
});
console.log(r);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment