Created
July 20, 2014 16:26
-
-
Save allex/ebdb822006afb8b1c2df to your computer and use it in GitHub Desktop.
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
// Author: Allex Wang | |
// GistID: ebdb822006afb8b1c2df | |
// GistURL: https://gist.github.com/ebdb822006afb8b1c2df | |
// Simple sprintf implement | |
var sprintf = function(format) { | |
var return_str = new String(format); | |
var match; | |
var reg = /%([osif])/i; | |
var before, after, replacement; | |
var argIndex = 1; | |
do { | |
match = reg.exec(return_str); | |
if (match) { | |
before = return_str.substr(0, match.index); | |
after = return_str.substr(match.index + match[0].length, return_str.length); | |
replacement = ''; | |
switch (match[1]) { | |
case 'o': | |
if (typeof JSON === 'object' && JSON && JSON.stringify) { | |
replacement = JSON.stringify(arguments[argIndex]); | |
} else { | |
replacement = arguments[argIndex].toString(); | |
} | |
break; | |
case 'i': | |
replacement = parseInt(arguments[argIndex]).toString() | |
break; | |
case 'f': | |
replacement = arguments[argIndex].toFixed(3) | |
break; | |
case 's': | |
replacement = String(arguments[argIndex]) | |
} | |
return_str = before + replacement + after; | |
argIndex++; | |
} | |
} while (match); | |
return return_str; | |
}; | |
console.log(sprintf('Hi, %s, count: %f, data: %o', 'Allex', 1.2222444, {json:1})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment