Undescorize, Dasherize, Capitalize String Prototype
Just share some useful functions to extends the String object :
Underscorize
"SomeStringTesting'".underscorize()
will return
some_string_testing
String.prototype.underscorize = function() {
return this.replace(/[A-Z]/g, function(char, index) {
return (index !== 0 ? '_' : '') + char.toLowerCase();
});
};
Dasherize
"SomeStringTesting".dasherize()
will return
some-string-testing
String.prototype.dasherize = function() {
return this.replace(/[A-Z]/g, function(char, index) {
return (index !== 0 ? '-' : '') + char.toLowerCase();
});
};
Capitalize first letter
"awesome string testing".capitalizeFirstLetter()
will return
Awsome string testing
String.prototype.capitalizeFirstLetter = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
};
Capitalize first letter of all words
"awesome string testing".capitalizeEachWord()
will return
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(" ");
};Written by iam4x
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#String
Authors
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#