Last active
August 29, 2015 14:19
-
-
Save beenhere4hours/a3ad8333c492043a4274 to your computer and use it in GitHub Desktop.
Extending the String class with helpful functions for templating
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
/** | |
* Javascript implementation of String.format or printf | |
* | |
* example of usage | |
* 'vincenty lat1: {0} lon1: {1} lat2: {2} lon2: {3}'.format(lat1, lon1, lat2, lon2) | |
* | |
* outputs | |
* vincenty lat1: 40.689247 lon1: -74.044502 lat2: 40.7747222222 lon2: -73.8719444444 | |
* | |
* http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format/4673436#comment46715555_4673436 | |
* | |
*/ | |
if (typeof String.prototype.format === 'undefined') { | |
String.prototype.format = function () { | |
"use strict"; | |
var args = arguments; | |
return this.replace(/\{(\d+)\}/g, function (match, number) { | |
return typeof args[number] !== 'undefined' ? args[number] : match; | |
}); | |
}; | |
} | |
// TODO: untested | |
// inspired by Douglas Crockford's Javascript the Good Parts | |
// JSLint issues | |
// insecure ^ --> '^' '.' match more material than might be expected, allowing attackers to confuse applications. | |
// These forms should not be used when validating in secure applications. | |
if (typeof String.prototype.supplant === 'undefined') { | |
String.prototype.supplant = function (o) { | |
return this.replace(/{([^{}]*)}/g, function (match, number) { | |
return typeof o[number] === 'string' ? o[number] : match; | |
}); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment