【问题标题】:How to remove more than one whitespace character from HTML?如何从 HTML 中删除多个空白字符?
【发布时间】:2012-08-18 06:04:22
【问题描述】:

我想删除来自用户端的额外空格,但我无法预测 HTML 的格式。

例如:

<p> It's interesting that you would try cfsetting, since nothing in it's
documentation would indicate that it would do what you are asking.
Unless of course you were mis-reading what "enableCFoutputOnly" is
supposed to do.


</p>



<p>



It's interesting that you would try cfsetting, since nothing in it's
documentation would indicate that it would do what you are asking.
Unless of course you were mis-reading what "enableCFoutputOnly" is
supposed to do.</p>

请指导我如何从 HTML 中删除多个空白字符。

【问题讨论】:

    标签: html coldfusion whitespace coldfusion-8


    【解决方案1】:

    您可以使用正则表达式通过循环遍历结果,用单个空格替换任何多个空格字符的情况,直到不再存在多个空格:

    lastTry = "<p>   lots of space    </p>";
    nextTry = rereplace(lastTry,"\s\s", " ", "all");
    while(nextTry != lastTry) {
      lastTry = nextTry;
      nextTry = REReplace(lastTry,"\s\s", " ", "all");
    }
    

    在 CF10 中测试工作。

    【讨论】:

    • 这是一个非常啰嗦的方法!最快的方法可能是:input.replaceAll('\s\s+',' ') 或者,为了避免用空格替换换行符,也可以这样做:input.replaceAll('(\s)\s+','$1')(即将所有空格压缩到每个链中的第一个空格)。
    • 当然,所有这些都会修改 pre/etc 中的内容——如果这样的事情很重要,那么适当的 HTML 解析器是解决这个问题的更好方法,特别是因为很有可能已经有了'tidy' 方法来处理这种情况。
    • 旁注:由于 OP 已明确将问题标记为 CF8,因此使用 CF10 进行测试有点多余(但是,这里的一切都很简单,从 CF7 开始应该可以正常工作。)
    • 啊,我认为 input.replaceAll('(\s)\s+','$1') 是一个更好的解决方案。为什么不把它作为一个单独的答案呢?
    • re:旁注:“这里的一切都很简单,从 CF7 开始应该可以正常工作”——完全正确。
    【解决方案2】:

    如果您出于完全的懒惰而不想通过代码来完成它

    => http://jsbeautifier.org/

    如果您想通过代码来实现,那么正则表达式将是另一种选择

    【讨论】:

      【解决方案3】:

      应该这样做:

      <cfscript>
        string function stripCRLFAndMultipleSpaces(required string theString) {
          local.result = trim(rereplace(trim(arguments.theString), "([#Chr(09)#-#Chr(30)#])", " ", "all"));
          local.result = trim(rereplace(local.result, "\s{2,}", " ", "all"));
          return local.result;
        }
      </cfscript>
      

      【讨论】:

      • 我对 Russ 的回答的所有 cmets 也适用于此 - 这将破坏 pre 标签的格式,并且因为它将换行符转换为空格也有可能破坏 JavaScript 功能。
      猜你喜欢
      • 2018-03-04
      • 1970-01-01
      • 1970-01-01
      • 2016-12-30
      • 1970-01-01
      • 1970-01-01
      • 2015-10-08
      • 2016-05-30
      • 2012-06-21
      相关资源
      最近更新 更多