Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
safer string formatting
// Inspired by http://bit.ly/juSAWl
// 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
console.log(
"{0} is a {1} and likes to {2}".format("Tim", "programmer", "kick potatoes");
); // Tim is a programmer and likes to kick potatoes
// object handling
console.log(
"{0} is my favorite object".format({lol:'hi'})
); // {"lol":"hi"} is my favorite object
// array handling
console.log(
"my array: {0}".format([1,2,3,4,5])
); // my array: [1,2,3,4,5]
// multiple reuse
console.log(
"{0} is a {0} is a {0}".format("steve jobes")
); // ""steve jobes" is a "steve jobes" is a "steve jobes""
@valtron

Has a little bug if the arguments contain /{\d+}/: http://jsfiddle.net/EGyrM/1/

@simarsenault

Thank you. Perfect for what I need!

@tetri

consider using the best option in replaceAll method: http://jsperf.com/replace-all-vs-split-join/25

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.