在JavaScript中修剪字符串?

如何修剪JavaScript中的字符串? git


#1楼

不知道什么错误能够隐藏在这里,可是我用这个: github

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

另外一种尝试: app

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

#2楼

我有一个使用trim的库。 所以经过使用如下代码解决了它。 this

String.prototype.trim = String.prototype.trim || function(){ return jQuery.trim(this); };

#3楼

使用本机JavaScript方法: String.trimLeft()String.trimRight()String.trim()es5


IE9 +和全部其余主要浏览器均支持String.trim()spa

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


String.trimLeft()String.trimRight()是非标准的,但除IE以外的全部主要浏览器均支持 prototype

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


使用polyfill能够轻松实现IE支持: code

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, '');
        };
    }
}

#4楼

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, " ");
};

Matt Duereg无耻地偷走了。 ip


#5楼

对于IE9 +和其余浏览器

function trim(text) {
    return (text == null) ? '' : ''.trim.call(text);
}
相关文章
相关标签/搜索