Thursday, July 24, 2014

Javascript: trim function support in all browsers



In Javascript, when we want to remove spaces in a string, we would be using trim function which is supported in all major browsers. See below code to use trim function in Javascript.

var str = "     message to trim    ";
document.write(str.trim());  // this code will prints as message to trim in the body.

But the above trim() function doesnot support in IE. To support the same functionality in IE too, add the below code to work as expected.

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