Last Updated: February 25, 2016
·
4.893K
· 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"

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside