Trim string in JavaScript?

后端 未结 20 2347
不知归路
不知归路 2020-11-21 06:27

How do I trim a string in JavaScript? That is, how do I remove all whitespace from the beginning and the end of the string in JavaScript?

20条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 06:58

    Trim code from angular js project

    var trim = (function() {
    
      // if a reference is a `String`.
      function isString(value){
           return typeof value == 'string';
      } 
    
      // native trim is way faster: http://jsperf.com/angular-trim-test
      // but IE doesn't have it... :-(
      // TODO: we should move this into IE/ES5 polyfill
    
      if (!String.prototype.trim) {
        return function(value) {
          return isString(value) ? 
             value.replace(/^\s*/, '').replace(/\s*$/, '') : value;
        };
      }
    
      return function(value) {
        return isString(value) ? value.trim() : value;
      };
    
    })();
    

    and call it as trim(" hello ")

提交回复
热议问题