Skip to content

Instantly share code, notes, and snippets.

@cdmckay
Last active August 29, 2015 14:25
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 cdmckay/a18704b61e40a4546ad0 to your computer and use it in GitHub Desktop.
Save cdmckay/a18704b61e40a4546ad0 to your computer and use it in GitHub Desktop.
An ES6 template string-compatible format method
if (!String.prototype.format) {
(function() {
'use strict';
var TEMPLATE_REGEXP = /\${\s*([$_a-z][$_a-z0-9]*)\s*}/ig;
var format = function (env) {
return this.replace(TEMPLATE_REGEXP, function (_, expr) {
return env[expr];
});
};
if (Object.defineProperty) {
Object.defineProperty(String.prototype, 'format', {
'value': format,
'configurable': true,
'writable': true
});
} else {
String.prototype.format = format;
}
})();
}
// This format method is handy because it provides a migration pathway to using ES6 template strings
// For example, this
// > var test = 123;
// > "this is a ${test}".format({ test: test });
// becomes
// `this is a ${test}`;
// Example
var test = 123;
"this is a ${test}".format({ test: test });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment