jquery.sprintf.js 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /**
  2. * sprintf and vsprintf for jQuery
  3. * somewhat based on http://jan.moesen.nu/code/javascript/sprintf-and-printf-in-javascript/
  4. *
  5. * Copyright (c) 2008 Sabin Iacob (m0n5t3r) <iacobs@m0n5t3r.info>
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * @license http://www.gnu.org/licenses/gpl.html
  17. * @project jquery.sprintf
  18. */
  19. (function($){
  20. var formats = {
  21. 'b': function(val) {return parseInt(val, 10).toString(2);},
  22. 'c': function(val) {return String.fromCharCode(parseInt(val, 10));},
  23. 'd': function(val) {return parseInt(val, 10);},
  24. 'u': function(val) {return Math.abs(val);},
  25. 'f': function(val, p) {
  26. p = parseInt(p, 10);
  27. val = parseFloat(val);
  28. if(isNaN(p && val)) {
  29. return NaN;
  30. }
  31. return p && val.toFixed(p) || val;
  32. },
  33. 'o': function(val) {return parseInt(val, 10).toString(8);},
  34. 's': function(val) {return val;},
  35. 'x': function(val) {return ('' + parseInt(val, 10).toString(16)).toLowerCase();},
  36. 'X': function(val) {return ('' + parseInt(val, 10).toString(16)).toUpperCase();}
  37. };
  38. var re = /%(?:(\d+)?(?:\.(\d+))?|\(([^)]+)\))([%bcdufosxX])/g;
  39. var dispatch = function(data){
  40. if(data.length == 1 && typeof data[0] == 'object') { //python-style printf
  41. data = data[0];
  42. return function(match, w, p, lbl, fmt, off, str) {
  43. return formats[fmt](data[lbl]);
  44. };
  45. } else { // regular, somewhat incomplete, printf
  46. var idx = 0;
  47. return function(match, w, p, lbl, fmt, off, str) {
  48. if(fmt == '%') {
  49. return '%';
  50. }
  51. return formats[fmt](data[idx++], p);
  52. };
  53. }
  54. };
  55. $.extend({
  56. sprintf: function(format) {
  57. var argv = Array.apply(null, arguments).slice(1);
  58. return format.replace(re, dispatch(argv));
  59. },
  60. vsprintf: function(format, data) {
  61. return format.replace(re, dispatch(data));
  62. }
  63. });
  64. })(jQuery);