Skip to content

@tbranyen /string.format.js

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
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""

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


Thank you. Perfect for what I need!


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
Something went wrong with that request. Please try again.