javascript tutorial - [5 Solutions] Trim a string in JavaScript - javascript - java script - javascript array



Problem:

How do we trim a string in JavaScript?

Solution 1:

This is generally recommended when extending Native Objects! Note that the added property is enumerable unless you use ES5 Object.defineProperty!

if (!String.prototype.trim) {
    (function() {
        // Make sure we trim BOM and NBSP
        var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
        String.prototype.trim = function() {
            return this.replace(rtrim, '');
        };
    })();
}
click below button to copy the code. By JavaScript tutorial team

Solution 2:

The trim from jQuery is convenient if we were already using this framework.

$.trim('  your string   ');
click below button to copy the code. By JavaScript tutorial team

Solution 3:

ideally any attempt to prototype the trim method should really check to see if it already exists first.

if(!String.prototype.trim){  
  String.prototype.trim = function(){  
    return this.replace(/^\s+|\s+$/g,'');  
  };  
}
click below button to copy the code. By JavaScript tutorial team

Solution 4:

There are lot of implementations that can be used.

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

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

click below button to copy the code. By JavaScript tutorial team

Solution 5:

/**
 *  Trim string. Actually trims all control characters.
 *  Ignores fancy Unicode spaces. Forces to string.
 */
function trim(str) {
    str = str.toString();
    var begin = 0;
    var end = str.length - 1;
    while (begin <= end && str.charCodeAt(begin) < 33) { ++begin; }
    while (end > begin && str.charCodeAt(end) < 33) { --end; }
    return str.substr(begin, end - begin + 1);
}
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Trim a string in JavaScript