What is the best way to trim() in javascript

前端 未结 19 1929
眼角桃花
眼角桃花 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:03

    I use this with native JavaScript

    // Adding trim function to String object if its not there
    if(typeof String.prototype.trim !== 'function') {
      String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g, '');
      }
    }
    

    Use like this

    var myString = "                  some text                  ";
    
    alert(myString.trim());
    

    Example

    // Adding trim function to String object if its not there
    if(typeof String.prototype.trim !== 'function') {
      String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g, '');
      }
    }
    
    var str = "      some text              ";
    console.log(str.trim());

提交回复
热议问题