String strip() for JavaScript?

rawrrrrrrrr picture rawrrrrrrrr · Sep 13, 2009 · Viewed 294.7k times · Source

What's a clean and efficient JavaScript implementation to strip leading and trailing spaces from a string?

For example:

" dog"

"dog "

" dog "

" dog "

all get turned into

"dog"

Answer

David Andres picture David Andres · Sep 13, 2009

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.