Basta compartilhar algumas funções úteis para estender o objeto String:
Underscorize
"SomeStringTesting'".underscorize()
retornarásome_string_testing
String.prototype.underscorize = function() {
return this.replace(/[A-Z]/g, function(char, index) {
return (index !== 0 ? '_' : '') + char.toLowerCase();
});
};
Dasherize
"SomeStringTesting".dasherize()
retornarásome-string-testing
String.prototype.dasherize = function() {
return this.replace(/[A-Z]/g, function(char, index) {
return (index !== 0 ? '-' : '') + char.toLowerCase();
});
};
Capitalize a primeira letra
"awesome string testing".capitalizeFirstLetter()
retornaráAwsome string testing
String.prototype.capitalizeFirstLetter = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
};
Capitalize a primeira letra de todas as palavras
"awesome string testing".capitalizeEachWord()
retornaráAwsome String Testing
String.prototype.capitalizeEachWord = function() {
var index, word, words, _i, _len;
words = this.split(" ");
for (index = _i = 0, _len = words.length; _i < _len; index = ++_i) {
word = words[index].charAt(0).toUpperCase();
words[index] = word + words[index].substr(1);
}
return words.join(" ");
};