Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
safer string formatting
// Inspired by
// Augment String.prototype to allow for easier formatting. This implementation
// doesn't completely destroy any existing String.prototype.format functions,
// and will stringify objects/arrays.
String.prototype.format = function(i, safe, arg) {
function format() {
var str = this, len = arguments.length+1;
// For each {0} {1} {n...} replace with the argument in that position. If
// the argument is an object or an array it will be stringified to JSON.
for (i=0; i < len; arg = arguments[i++]) {
safe = typeof arg === 'object' ? JSON.stringify(arg) : arg;
str = str.replace(RegExp('\\{'+(i-1)+'\\}', 'g'), safe);
return str;
// Save a reference of what may already exist under the property native.
// Allows for doing something like: if("".format.native) { /* use native */ }
format.native = String.prototype.format;
// Replace the prototype property
return format;
// include string.format.js
// simple string replacement
"{0} is a {1} and likes to {2}".format("Tim", "programmer", "kick potatoes");
); // Tim is a programmer and likes to kick potatoes
// object handling
"{0} is my favorite object".format({lol:'hi'})
); // {"lol":"hi"} is my favorite object
// array handling
"my array: {0}".format([1,2,3,4,5])
); // my array: [1,2,3,4,5]
// multiple reuse
"{0} is a {0} is a {0}".format("steve jobes")
); // ""steve jobes" is a "steve jobes" is a "steve jobes""

valtron commented Jan 3, 2012

Has a little bug if the arguments contain /{\d+}/:

Thank you. Perfect for what I need!

tetri commented Sep 3, 2014

consider using the best option in replaceAll method:

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