1. 程式人生 > >js中去除字符串兩邊的空格

js中去除字符串兩邊的空格

ace 代碼 this span return his ret repl 字符串

在提交表單的時候會需要去除字符串兩邊的空格,代碼如下:

/*去除字符串兩邊空格*/
String.prototype.trim = function() {
    return this.replace(/^\s*|\s*$/g, "");
}
/*去除字符串左邊空格*/
String.prototype.ltrim = function(){
    return this.replace(/^\s*/g,"")
}
/*去除字符串右邊空格*/
String.prototype.rtrim = function(){
    return this.replace(/\s*$/g,"")
}

例:str = " fsfa fasdf sfas ";

  str.trim() == "fsfa fasdf sfas";

js中去除字符串兩邊的空格