Last Updated: February 25, 2016
·
4.398K
· revgum

Javascript string trimming in IE8--

Much to my dismay, many of my users are still stuck using IE8. This has caused me to perform far too many mental gymnastics over the years coding Javascript and styling with CSS. Occasionally I have a need to trim leading or trailing spaces from a string, and I always misplace the proper regex for it in Javascript. No longer!

If String.trim() doesn't exist in the poor ol' browser my user has running, lets make it;

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

" foo ".trim();  // returns "foo"