Created
July 30, 2010 16:00
-
-
Save mckamey/500765 to your computer and use it in GitHub Desktop.
.NET-style String.Format implementation for JavaScript
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
/*global JSON */ | |
if ("undefined" === typeof String.format) { | |
// String.format: populates a format string with an ordered list of values | |
/*string*/ String.format = function(/*params*/) { | |
var args = arguments, | |
num = args.length, | |
str = args[0]; | |
if (!num || !str) { | |
return str||""; | |
} | |
for (var i=1; i<num; i++) { | |
var value = args[i]; | |
if (typeof value === "object") { | |
value = JSON.stringify(value); | |
} | |
str = str.replace(new RegExp("\\{" + (i-1) + "\\}", "g"), String(value)); | |
} | |
return str; | |
}; | |
} | |
if ("undefined" === typeof String.formatKeys) { | |
// String.formatKeys: populates a format string with a dictionary | |
/*string*/ String.formatKeys = function(/*string*/ str, /*object*/ values) { | |
if (!str || !values || typeof values !== "object") { | |
return str||""; | |
} | |
for (var key in values) { | |
if (key && values.hasOwnProperty(key)) { | |
var value = values[key]; | |
if (typeof value === "object") { | |
value = JSON.stringify(value); | |
} | |
str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), String(value)); | |
} | |
} | |
return str; | |
}; | |
} | |
if ("undefined" === typeof String.prototype.trim) { | |
/*string*/ String.prototype.trim = function () { | |
return this.replace(/^\s*|\s*$/g, ""); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment