Mohan Ram
Mohan Ram

Reputation: 8463

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?

Upvotes: 4

Views: 3140

Answers (3)

Till
Till

Reputation: 3154

From the jquery source:

// Used for trimming whitespace
    trimLeft = /^\s+/,
    trimRight = /\s+$/,

// Use native String.trim function wherever possible
trim: trim ?
function( text ) {
    return text == null ?
        "" :
        trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
    return text == null ?   "" : text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
},

Upvotes: 1

Stephen
Stephen

Reputation: 18917

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, '');
        };
    }     
})();

Upvotes: 10

Headshota
Headshota

Reputation: 21449

Here are some functions that might help try them:

http://www.webtoolkit.info/javascript-trim.html

Upvotes: 0

Related Questions