Sprintf for Javascript
Occasional articles on Dynamic HTML, Javascript, Ajax, CSS, Perl, PHP and other Web Technologies.One vital programming construct that's missing from Javascript is the sprintf function. In C and other languages, sprintf (and its sister function printf) allow the programmer to format strings using a compact set of rules.
Sprintf is also available in a large variety of other languages, such as python and PHP, but is sadly lacking from the Javascript specification.
Features
Supports the following features
- %b, %c, %d, %e, %f, %o, %s, %u, %x, %X
- zero-padding and precision (e.g. %3.3f)
- %% is converted to HTML escape sequence
- Argument swapping
- JsUnit testcase available on request.
// Add dummy console.info if not using Firebug. if (!("console" in window) || !("firebug" in console)) { window.console = {}; window.console.info = function() {} } function sprintf() { if (!arguments || arguments.length < 1 || !RegExp) { return; } var str = arguments[0]; var re = /([^%]*)%('.|0|\d\$)?(-)?(\d+)?(\.\d+)?(%|b|c|d|e|u|f|o|s|x|X)(.*)/; var a = b = [], numSubstitutions = 0, numMatches = 0; while (a = re.exec(str)) { var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4]; var pPrecision = a[5], pType = a[6], rightPart = a[7]; numMatches++; if (pType == '%') { padding=''; subst = '%'; } else { numSubstitutions++; if (numSubstitutions >= arguments.length) { console.info('Error! Not enough function arguments (' + (arguments.length - 1) + ', excluding the string)\n' + 'for the number of substitution parameters in string (' + numSubstitutions + ' so far).'); } var param = arguments[numSubstitutions]; var pad = ''; if (pPad) { if (pPad.substr(1,1) == '$') { // Arg swapping param = arguments[parseInt(pPad)]; } else if (pPad.substr(0,1) == "'") { // Custom pad character pad = pPad.substr(1,1); } else { // Pad with zeros pad = pPad; } } var justifyRight = true; if (pJustify && pJustify === "-") justifyRight = false; var minLength = -1; if (pMinLength) minLength = parseInt(pMinLength); var precision = -1; if (pPrecision && (pType == 'e'|| pType == 'f')) { precision = parseInt(pPrecision.substring(1)); } var subst = param; switch (pType) { case 'b': subst = parseInt(param).toString(2); break; case 'c': subst = String.fromCharCode(parseInt(param)); break; case 'd': subst = parseInt(param) ? parseInt(param) : 0; break; case 'e': subst = precision>-1 ? param.toExponential(precision) : param.toExponential(); break; case 'u': subst = Math.abs(param); break; case 'f': subst = (precision > -1) ? Math.round(parseFloat(param) * Math.pow(10, precision)) / Math.pow(10, precision) : parseFloat(param); break; case 'o': subst = parseInt(param).toString(8); break; case 's': subst = param; break; case 'x': subst = ('' + parseInt(param).toString(16)).toLowerCase(); break; case 'X': subst = ('' + parseInt(param).toString(16)).toUpperCase(); break; } var padLeft = minLength - subst.toString().length; if (padLeft > 0) { var arrTmp = new Array(padLeft+1); var padding = arrTmp.join(pad?pad:" "); } else { var padding = ""; } } str = leftpart + padding + subst + rightPart; } return str; }
License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Additional Credits
This implementation is based on work by
Jan
Moesen and
Robert Pollard.