<script>
s="  a b  c  d  ";
s=s.replace(/\s/g,"x")
document.write(s);
</script>
不知道你是不是要这种结果

解决方案 »

  1.   

    <script>
    s="  a b  c  d  ";
    s=s.replace(/\s+/g,"x")
    document.write(s);
    </script>
    多个空格替换成一个“x”
      

  2.   

    试一试下面的代码,应该是你想要的:
    <script>
    //函数中的nPos, cTail变量是必要的,否则执行RegExp.$2.replace()后,
    //RegExp.lastIndex==0,RegExp.$3==""
    function ReplaceSpace ( Field ) {
       var cStr = Field.value, cResult = "", nPos, cTail;
       var re = /(.*?)("[^"]*?")([^"]*)/;
       for ( ; re.test ( cStr ); cStr = cStr.substr ( nPos, cStr.length ) ) {
          nPos = RegExp.lastIndex;
          cTail = RegExp.$3;
          cResult += RegExp.$1 + RegExp.$2.replace ( /\s+/g, "" ) + cTail;
       }
      // return ( cResult );
       alert ( cResult );
    }</script>
    <form>
    <input name="t1" Size="60" nMaxLength="60" Value='a   b  c  d  "  a b   c  d  " e  f  g " qqq  " h i j' onblur="ReplaceSpace(this)"><br>
    <input name="t2" Size="60" nMaxLength="60" Value='a   b  c  d  "  a b   c  d  " e  f  g " qqq  " h i j' onblur="ReplaceSpace(this)"><br>
    </form>
      

  3.   

    引号多了不好办呀,因为不好判断是第一、二引号中的还是第二、三引号中的,如果是全角引号就好了......
    可能会出现把
    a   b  c  d  "  a b   c  d  " e  f  g " qqq  " h i j
    替换成
    a   b  c  d  "  a b   c  d  "xexxfxxgx" qqq  " h i j
    的情况
      

  4.   

    哦,是将引号中的空格替换成x,请将
       cResult += RegExp.$1 + RegExp.$2.replace ( /\s+/g, "" ) + cTail;
    中的""改为"x",抱歉!
      

  5.   

    shuangren(双刃) :我写的那个函数,按楼主给的例子,不会出现你说的那种情况。请注意正则("[^"]*?")中的3个"。
      

  6.   

    <script>
    s = 'a   b  c  d  "  a b   c  d  " e  f  g " qqq  " h i j';
    o = s.match(/(".*?")/g);
    for(i=0;i<o.length;i++) {
      s = s.replace(o[i],o[i].replace(/ /g,"x"));
    }
    document.write(s);
    </script>