Search code examples
javascriptjqueryextend

How to Extend JavaScript with global method like .toLowerCase()?


I'm trying to find out how to extend JavaScript with some of my own methods similar to toLowerCase()

Say I wanted a capitalize() or addUnderscores(), really whatever. I'm assuming there is a way to extend or overwrite existing ones.

Also is there a way to do it with jQuery?


Solution

  • Not with jQuery. Just extend the prototype of the specific type you need...

    if (!String.prototype.capitalize) {
        String.prototype.capitalize = function() {
            return this.toUpperCase();
        }
    }
    
    'foobar'.capitalize(); // 'FOOBAR'
    

    In the function, this will be the string on which you called the method.