What is the best way to trim() in javascript

前端 未结 19 1948
眼角桃花
眼角桃花 2020-11-29 06:32

The question says it all; JS doesn\'t seem to have a native trim() method.

19条回答
  •  清歌不尽
    2020-11-29 07:05

    Use Ariel Flesler's fast trim function:

    // Licensed under BSD
    function myBestTrim( str ){
     var start = -1,
      end = str.length;
     while( str.charCodeAt(--end) < 33 );
     while( str.charCodeAt(++start) < 33 );
     return str.slice( start, end + 1 );
    };
    

    My solution, though, would be this (because the String object in Firefox 3.5 and above already has a trim method):

    String.prototype.trim = String.prototype.trim || function () {
        var start = -1,
            end   = this.length;
    
        while( this.charCodeAt(--end) < 33 );
        while( this.charCodeAt(++start) < 33 );
    
        return this.slice( start, end + 1 );
    };
    

提交回复
热议问题