public
Created

safer string formatting

  • Download Gist
string.format.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
// 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;
 
}();
using.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// 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""

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

Thank you. Perfect for what I need!

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.