Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent for $.trim in Javascript?

$.trim(value);

The above jquery code would trim the text. I need to trim the string using Javascript.

I tried:

link_content = "    check    ";
trim_check = link_content.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,'');

How to use trim in javascript? Equivalent of $.trim() of jQuery?

like image 305
Mohan Ram Avatar asked Dec 22 '22 13:12

Mohan Ram


1 Answers

JavaScript 1.8.1 includes the trim method on String objects. This code will add support for the trim method in browsers that do not have a native implementation:

(function () {
    if (!String.prototype.trim) {
        /**
         * Trim whitespace from each end of a String
         * @returns {String} the original String with whitespace removed from each end
         * @example
         * ' foo bar    '.trim(); //'foo bar'
         */
        String.prototype.trim = function trim() {
            return this.toString().replace(/^([\s]*)|([\s]*)$/g, '');
        };
    }     
})();
like image 92
Stephen Avatar answered Jan 12 '23 16:01

Stephen