在JavaScript中修剪字符串?

Vin*_*nod 1285 javascript string trim

如何修剪JavaScript中的字符串?

Pra*_*hra 884

自IE9 +以来的所有浏览器都有trim().

对于那些不支持的浏览器trim(),您可以使用MDN中的此polyfill :

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, '');
        };
    })();
}
Run Code Online (Sandbox Code Playgroud)

看到这个:

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

String.prototype.ltrim=function(){return this.replace(/^\s+/,'');};

String.prototype.rtrim=function(){return this.replace(/\s+$/,'');};

String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');};
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,在jQuery中,`$ .trim(str)`总是可用的. (87认同)

bar*_*ron 480

如果您已经在使用该框架,那么jQuery的修剪很方便.

$.trim('  your string   ');
Run Code Online (Sandbox Code Playgroud)

我经常使用jQuery,因此使用它修剪字符串对我来说很自然.但是有可能在那里对jQuery产生强烈反对?:)


scu*_*ffe 165

虽然上面有一堆正确的答案,但应该注意StringJavaScript 中的对象有一个ECMAScript 5的本机.trim()方法.因此,理想情况下,任何对trim方法进行原型设计的尝试都应该检查它是否已经存在.

if(!String.prototype.trim){  
  String.prototype.trim = function(){  
    return this.replace(/^\s+|\s+$/g,'');  
  };  
}
Run Code Online (Sandbox Code Playgroud)

本机添加: JavaScript 1.8.1/ECMAScript 5

因此支持:

Firefox:3.5+

Safari:5+

Internet Explorer:IE9 +(仅在标准模式下!)http://blogs.msdn.com/b/ie/archive/2010/06/25/enhanced-scripting-in-ie9-ecmascript-5-support-and-more的.aspx

Chrome:5+

歌剧:10.5+

ECMAScript 5支持表:http://kangax.github.com/es5-compat-table/


Gum*_*mbo 127

很多实现可以使用.最明显的似乎是这样的:

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

" foo bar ".trim();  // "foo bar"
Run Code Online (Sandbox Code Playgroud)


Mar*_*son 46

这里的简单版本JavaScript trim的一般功能是什么?

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


Vij*_*raj 28

我知道这个问题已在三年前被问过了.现在,它String.trim()是在JavaScript中本地添加的.例如,你可以直接修改如下,

document.getElementById("id").value.trim();
Run Code Online (Sandbox Code Playgroud)

  • 这不适用于ie版本,如果可以的话,使用jQuery methd $ .trim(str) (3认同)

Abl*_*ias 22

如果您使用的是jQuery,请使用该jQuery.trim()功能.例如:

if( jQuery.trim(StringVariable) == '')
Run Code Online (Sandbox Code Playgroud)


小智 20

Flagrant Badassery有11种不同的装饰和基准信息:

http://blog.stevenlevithan.com/archives/faster-trim-javascript

令人惊讶的是基于正则表达式比传统循环慢.


这是我个人的.这段代码很旧!我为JavaScript1.1和Netscape 3编写了它,之后它只是略有更新.(原文使用String.charAt)

/**
 *  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);
}
Run Code Online (Sandbox Code Playgroud)


Web*_*ner 13

使用本地JavaScript方法:String.trimLeft(),String.trimRight(),和String.trim().


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

'  Hello  '.trim()  //-> 'Hello'
Run Code Online (Sandbox Code Playgroud)


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

'  Hello  '.trimLeft()   //-> 'Hello  '
'  Hello  '.trimRight()  //-> '  Hello'
Run Code Online (Sandbox Code Playgroud)


然而,使用polyfill可以轻松支持IE:

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, '');
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @Brad我还没有看到有人提到`trimLeft`或`trimRight`. (4认同)

Emi*_*ort 11

现在,您可以使用本机Javascript实现的string.trim()

var orig = "   foo  ";
console.log(orig.trim());//foo
Run Code Online (Sandbox Code Playgroud)

也可以看看


yck*_*art 10

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

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

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

String.prototype.trimFull = String.prototype.trimFull || function () {
    return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, "").replace(/\s+/g, " ");
};
Run Code Online (Sandbox Code Playgroud)

Matt duereg无耻地偷走了.


rab*_*rab 7

修剪角度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;
  };

})();
Run Code Online (Sandbox Code Playgroud)

并称之为 trim(" hello ")


Beh*_*adi 5

使用简单的代码

var str = "       Hello World!        ";
alert(str.trim());
Run Code Online (Sandbox Code Playgroud)

浏览器支持

Feature         Chrome  Firefox Internet Explorer   Opera   Safari  Edge
Basic support   (Yes)   3.5     9                   10.5    5       ?
Run Code Online (Sandbox Code Playgroud)

对于旧浏览器添加原型

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
}
Run Code Online (Sandbox Code Playgroud)