Last Updated: February 25, 2016
·
5.796K
· iam4x

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(" ");
};