Last active
August 29, 2015 14:25
-
-
Save cdmckay/a18704b61e40a4546ad0 to your computer and use it in GitHub Desktop.
An ES6 template string-compatible format method
This file contains hidden or 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
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