Skip to content

Instantly share code, notes, and snippets.

@mckamey
Created July 30, 2010 16:00
Show Gist options
  • Save mckamey/500765 to your computer and use it in GitHub Desktop.
Save mckamey/500765 to your computer and use it in GitHub Desktop.
.NET-style String.Format implementation for JavaScript
/*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