JavaScript的字符串去空格

461 阅读1分钟

删除两端

String的原型方法trim()

trim() 方法会删除一个字符串两端的空白字符。在这个字符串里的空格包括所有的空格字符 (space, tab, no-break space 等)以及所有的行结束符(如 LF,CR)

var str = "  hello world   ";
alert(str.trim());  //"hello world"

兼容方案

正则

function myTrim(str) {
    if(String.prototype.trim) {
        return str.trim();
    }
    return str.replace(/^\s+(.*?)\s+$/g, "$1");
    //or
    //return str.replace(/^\s+/, "").replace(/\s+$/, "");
}

删除全部

如果在字符串中仅存在空格,没有制表符等空白符,那么可以使用split()和join()方法来去空白:

常规

var str = "   hello  world   !";
var result = str.split(" ").join("");
console.log(result);  //helloworld!

函数

var str = "\t hello world !"; var result = str.replace(/\s+/g, ""); console.log(result); //helloworld!