Functions floating around the web

This part is more for reference. The following functions are so common, that I thought my post would be incomplete without offering them. They are not my own.

String.prototype.capitalize = function() {
    return this.replace(/(&)?([a-z])([a-z]{2,})(;)?/ig, function (all, prefix, letter, word, suffix) {
        if (prefix && suffix) {
            return all;
        return letter.toUpperCase() + word.toLowerCase();

String.prototype.ltrim = function() {
    // remove "padding" before the string
    return this.replace(/^\s+/, '');

String.prototype.rtrim = function() {
    // remove "padding" after the string
    return this.replace(/\s+$/,'');

String.prototype.repeat = function( num )
    // repeat a string num times
    return new Array( num + 1 ).join( this );



  1. I feel I need to state my case for adding to a built-in object's prototype a little more clearly. I'm not suggesting that you modify any of the object's existing functions. Other libraries, and more likely, your own code, expect certain behavior that you should not interfere with. But, in adding a function to a built-in object's prototype, you in no way affect the expected behavior of the object.

    My DVD player has a standard size "slot" for a DVD. DVD manufacturers expect this, so I would never want to modify it. But, adding the ability for my DVD player to also stream Netflix is okay. A DVD doesn't care that the player also supports streaming, and the ability to stream in no way interferes with the operation of the DVD playing feature.

  2. String.prototype.isVowel = function() {
       if (['a','e','i','o','u'].indexOf(this) !== -1)
            return true;
            return false;

Leave a Reply

Your email address will not be published. Required fields are marked *