I had the need for a few String functions in JavaScript to manage some variances between data sources so I figured I'd share them. For example, from one source attributes in the JSON data would use underscores to separate words and in another it would uses dashes (my_attribute vs my-attribute). Also for simple data display, I wanted to titleize the attribute name for a label (My Attribute).
/**
* String.toCamelCase
*
* Convert a string to camel case, including hyphens and underscores
*/
String.prototype.toCamelCase = function() {
return this.replace(/^([A-Z])|[\s-_](\w)/g, function(match, p1, p2, offset) {
if (p2) return p2.toUpperCase();
return p1.toLowerCase();
});
};
/**
* String.dasherize
*
* Dasherize a string, including periods and underscores
*/
if (!String.prototype.dasherize) {
String.prototype.dasherize = function() {
return this.replace(/^([A-Z])|[\s\._](\w)/g, function(match, p1, p2, offset) {
if (p2) return "-" + p2.toLowerCase();
return p1.toLowerCase();
});
};
}
/**
* String.capitalize
*
* Capitalize the first letter of a string
*/
if (!String.prototype.capitalize) {
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
};
}
/**
* String.titleize
*
* Capitalize the first letter of every word in a string, also separates
* words by spaces if formally separated by dashes or underscores
*
*/
if (!String.prototype.titleize) {
String.prototype.titleize = function() {
return this.replace(/^([A-Z])|[\s-_](\w)/g, function(match, p1, p2, offset) {
if (p2) return " " + p2.toUpperCase();
return p1.toLowerCase();
}).capitalize();
};
}
No comments:
Post a Comment