Created
June 27, 2011 18:22
-
-
Save tbranyen/1049426 to your computer and use it in GitHub Desktop.
safer string formatting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
}(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
consider using the best option in replaceAll method: http://jsperf.com/replace-all-vs-split-join/25