str=str.replace(/(^\s*)|(\s*$)/g, "");

解决方案 »

  1.   

    function trim(value){
    var res = String(value).replace(/^[\s]+|[\s]+$/g,'');
    return res;
    }
      

  2.   

    自己来定义Trim LRrim RTrim
    <script language=javascript>
    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, "");}
    var s = "    leading and trailing spaces    ";
    window.alert(s + " (" + s.length + ")");
    s = s.Trim();
    window.alert(s + " (" + s.length + ")");
    </script>
      

  3.   

    http://www.csdn.net/expert/topic/806/806410.xml?temp=.3242456
      

  4.   

    自己写一个
    function LTrim(tempString){
      while (tempString.charAt(0) == ' ') {
        tempString= tempString.substring(1,tempString.length);
      }
      return tempString;
    }
    function RTrim(tempString){
      while (tempString.charAt(tempString.length - 1) == ' ') {
        tempString= tempString.substring(0,tempString.length - 1);
        }
      return tempString;
    }