Skip to content

Instantly share code, notes, and snippets.

@ox
Last active December 19, 2015 11:19
Show Gist options
  • Save ox/5946368 to your computer and use it in GitHub Desktop.
Save ox/5946368 to your computer and use it in GitHub Desktop.
printf bunny
var printf = function (str) {
var args = Array.prototype.slice.call(arguments)
console.log(str.split('%').map(function (e, i) {
return (e[0] === 'x' ? String(args[i]) + e.substr(1) : e)
}).join(''))
}
printf('hello world') // => hello world
printf('number: %x, string: %x', 1, 'foo') // => number: 1, string: foo
printf('number: %x, string: %x', 'lol', 1, 'foo') // => number: lol, string: 1
printf('%xnumber: %x, string: %x', 'lol', 1, 'foo') // => lolnumber: 1, string: foo
@thebyrd
Copy link

thebyrd commented Jul 8, 2013

"{0} is easier for {1}".format("this", "me")

String.prototype.format = function() {
    var formatted = this
    for (var i = 0; i < arguments.length; i++) {
        var regexp = new RegExp('\\{'+i+'\\}', 'gi')
        formatted = formatted.replace(regexp, arguments[i])
    }
    return formatted
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment