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


当前回答

不知道有什么虫子可以藏在这里,但我用这个:

var some_string_with_extra_spaces="   goes here    "
console.log(some_string_with_extra_spaces.match(/\S.*\S|\S/)[0])

或者这个,如果文本包含回车:

console.log(some_string_with_extra_spaces.match(/\S[\s\S]*\S|\S/)[0])

另一个尝试:

console.log(some_string_with_extra_spaces.match(/^\s*(.*?)\s*$/)[1])

其他回答

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

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

这里有一个非常简单的方法:

function removeSpaces(string){
return string.split(' ').join('');
}

使用简单的代码

var str = "       Hello World!        ";
alert(str.trim());

浏览器支持

Feature         Chrome  Firefox Internet Explorer   Opera   Safari  Edge
Basic support   (Yes)   3.5     9                   10.5    5       ?

为旧浏览器添加原型

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

使用原生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, '');
        };
    }
}

有很多实现可以使用。最明显的是这样的:

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

" foo bar ".trim();  // "foo bar"