【问题标题】:Odd Javascript String manipulation behaviour奇怪的 Javascript 字符串操作行为
【发布时间】:2013-07-04 09:15:46
【问题描述】:

我不是 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)
 }

现在,当函数获取currentHTML 和newHTML 的值时,它会将它们传递给正则表达式方法,这些方法旨在去除所有空格、回车符和制表符。然而,这并没有发生。没有错误,没有错误。通过,它丝毫没有改变变量。

【问题讨论】:

    标签: javascript string


    【解决方案1】:

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

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

    到这里:

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

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

    【讨论】:

    • 继续。我知道这会很烦人。将在 7 分钟内标记:)
    【解决方案2】:

    我认为你忘记关闭 if body.

    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)
    

    }

    【讨论】:

    • 我想我是在提取 SO 的相关代码时删除了它。不过谢谢! +1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-31
    • 1970-01-01
    • 1970-01-01
    • 2015-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多