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


当前回答

我为trim写了这个函数,当时.trim()函数在2008年的JS中还不可用。一些旧的浏览器仍然不支持.trim()函数,我希望这个函数可以帮助到一些人。

修剪函数

function trim(str)
{
    var startpatt = /^\s/;
    var endpatt = /\s$/;

    while(str.search(startpatt) == 0)
        str = str.substring(1, str.length);

    while(str.search(endpatt) == str.length-1)
        str = str.substring(0, str.length-1);   

    return str;
}

解释:函数trim()接受一个字符串对象,删除任何开头和结尾的空格(空格、制表符和换行符),并返回经过修剪的字符串。您可以使用此函数修改表单输入,以确保发送的数据是有效的。

函数的调用方法如下所示。

form.elements[i].value = trim(form.elements[i].value);

其他回答

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

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])

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

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

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

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

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

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

function removeSpaces(string){
return string.split(' ').join('');
}
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, " ");
};

无耻地从马特·杜雷格那里偷来的。