js去除字符串首尾空格

大家可能会说js删除字符串首尾空格有什么好说的, 哪个不会啊。确实,大家应该都会, 现在浏览器都支持, 不支持的可以使用ployfill,代码如下

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

之所以写这篇文章, 是我从java处得到了启发。大多的ployfill都会有恼人的正则, 真的很难理解。我来贴下java的trim

public String trim() {
    int len = value.length;
    int st = 0;
    char[] val = value;    /* avoid getfield opcode */
    while ((st < len) && (val[st] <= ' ')) {
        st++;
    }
    while ((st < len) && (val[len - 1] <= ' ')) {
        len--;
    }
    return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
}  

大家应该都能看得懂, java源码认为asc码小于' '都是空格字符,找到头部不是空格字符的索引, 再获取尾部不是空格字符的索引, 中间就是我们trim之后的字符了。那我来写一个js的trim

if (!String.prototype.trim) {
    String.prototype.trim = function () {
        var len = this.length;
        var st = 0;
        while((st < len) && (this[st] <= ' ')) {
            st++;
        }
        while((st < len) && (this[len - 1] <= ' ')){
            len--;
        }
        return ((st > 0) || (len < this.length)) ? this.substring(st, len - st) : this;
    };
}
原文地址:https://www.cnblogs.com/mingao/p/7503291.html