我如何从字符串的开始和结束删除所有空白?


当前回答

从angular js项目中修剪代码

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;
  };

})();

并将其命名为trim(" hello ")

其他回答

你可以使用纯JavaScript来实现:

function trimString(str, maxLen) {
if (str.length <= maxLen) {
return str;
}
var trimmed = str.substr(0, maxLen);
return trimmed.substr(0, trimmed.lastIndexOf(' ')) + '…';
}

// Let's test it

sentenceOne = "too short";
sentencetwo = "more than the max length";

console.log(trimString(sentenceOne, 15));
console.log(trimString(sentencetwo, 15));

使用原生JavaScript方法:String.trimLeft(), String.trimRight()和String.trim()。

在IE9+和所有其他主要浏览器中都支持String.trim():

'  Hello  '.trim()  //-> 'Hello'

String.trimLeft()和String.trimRight()是非标准的,但除IE之外的所有主流浏览器都支持

'  Hello  '.trimLeft()   //-> 'Hello  '
'  Hello  '.trimRight()  //-> '  Hello'

IE的支持很容易与polyfill:

if (!''.trimLeft) {
    String.prototype.trimLeft = function() {
        return this.replace(/^\s+/,'');
    };
    String.prototype.trimRight = function() {
        return this.replace(/\s+$/,'');
    };
    if (!''.trim) {
        String.prototype.trim = function() {
            return this.replace(/^\s+|\s+$/g, '');
        };
    }
}

下面是它的TypeScript格式:

var trim: (input: string) => string = String.prototype.trim
    ? ((input: string) : string => {
        return (input || "").trim();
    })
    : ((input: string) : string => {
        return (input || "").replace(/^\s+|\s+$/g,"");
    })

如果本机原型不可用,它将回退到正则表达式。

JavaScript修剪的通用函数是什么?

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

如果使用jQuery,请使用jQuery.trim()函数。例如:

if( jQuery.trim(StringVariable) == '')