奇怪的Javascript字符串操作行为

时间:2013-07-04 09:15:47

标签: javascript string

我不是Javascript专家,但我开始认为这有些奇怪!基本上,我写了这个函数:

 function onChange()
 {
      if(this.responseText.length != 0) {

       // Get the new HTML Page requested from the servlet.
       var currentHTML = new XMLSerializer().serializeToString(document);
       var newHTML = this.responseText;

       currentHTML = currentHTML.replace('/\s+/g','');
       currentHTML = currentHTML.replace('/[\n\r]/g','');
       currentHTML = currentHTML.replace('/\t/g','');

       newHTML = newHTML.replace('/\s+/g','');
       newHTML = newHTML.replace('/[\n\r]/g','');
       newHTML = newHTML.replace('/\t/g','');


       // (There's also some alerts here just to get the output)
 }

现在,当函数获得currentHTMLnewHTML的值时,它会通过正则表达式方法传递它们,这些方法旨在去除所有空格,回车符和制表符。但是,这种情况并没有发生。没有错误,没有错误。通过,它没有丝毫改变变量。

2 个答案:

答案 0 :(得分:5)

正则表达式文字不包含引号。你需要改变这个:

currentHTML.replace('/\s+/g','');

对此:

currentHTML.replace(/\s+/g,'');

此外,您的替换有点多余。 \s已匹配制表符和换行符(以及空格!)。

答案 1 :(得分:1)

我认为你忘了关闭身体。

function onChange()

{       if(this.responseText.length!= 0){

   // Get the new HTML Page requested from the servlet.
   var currentHTML = new XMLSerializer().serializeToString(document);
   var newHTML = this.responseText;

   currentHTML = currentHTML.replace('/\s+/g','');
   currentHTML = currentHTML.replace('/[\n\r]/g','');
   currentHTML = currentHTML.replace('/\t/g','');

   newHTML = newHTML.replace('/\s+/g','');
   newHTML = newHTML.replace('/[\n\r]/g','');
   newHTML = newHTML.replace('/\t/g','');

   }
   // (There's also some alerts here just to get the output)

}