Search code examples
javascripttrimstrip

String strip() for JavaScript?


How do I strip leading and trailing spaces from a string?

For example, " dog " should become "dog".


Solution

  • Use this:

    if(typeof(String.prototype.trim) === "undefined")
    {
        String.prototype.trim = function() 
        {
            return String(this).replace(/^\s+|\s+$/g, '');
        };
    }
    

    The trim function will now be available as a first-class function on your strings. For example:

    " dog".trim() === "dog" //true
    

    EDIT: Took J-P's suggestion to combine the regex patterns into one. Also added the global modifier per Christoph's suggestion.

    Took Matthew Crumley's idea about sniffing on the trim function prior to recreating it. This is done in case the version of JavaScript used on the client is more recent and therefore has its own, native trim function.