<script> s=" a b c d "; s=s.replace(/\s+/g,"x") document.write(s); </script> 多个空格替换成一个“x”
试一试下面的代码,应该是你想要的: <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>
引号多了不好办呀,因为不好判断是第一、二引号中的还是第二、三引号中的,如果是全角引号就好了...... 可能会出现把 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 的情况
<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>
s=" a b c d ";
s=s.replace(/\s+/g,"x")
document.write(s);
</script>
多个空格替换成一个“x”
<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>
可能会出现把
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
的情况
cResult += RegExp.$1 + RegExp.$2.replace ( /\s+/g, "" ) + cTail;
中的""改为"x",抱歉!
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>