-
-
Save inodb/d803600ba1b2068d6021 to your computer and use it in GitHub Desktop.
Python-like string format in JavaScript
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
/** | |
* 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