【问题标题】:Regex for trimming whitesprace around tags用于修剪标签周围空白的正则表达式
【发布时间】:2017-11-23 22:24:20
【问题描述】:

我目前正在使用.replace(/>\s+</g,'><') 删除 HTML 标记之间的空格。

这将替换:

<hello> a b c </hello> <world> x y z </world>

与:

<hello> a b c </hello><world> x y z </world>

我想更新这个函数以达到以下结果:

<hello>a b c</hello><world>x y z</world>

我将如何改写这个正则表达式以去除围绕内部标签内容的新行、空格和制表符?

【问题讨论】:

  • 一般来说,您不能使用正则表达式处理任意 HTML。在非常受限的情况下,它可能是可能的,例如,如果您知道目标 HTML 总是适合某些严格的形式。
  • @Pointy 看来我应该是安全的,只要我避免 &amp;lt;&amp;gt; 选择 &amp;lt;&amp;gt;
  • .replace(/(&gt;)\s+|\s+(&lt;)/g, "$1$2")
  • ^ 这对我来说似乎是一个答案,而不是评论。
  • 如果您必须在 XML 标记之前删除空格,那么您做错了。你想用它做什么?

标签: javascript regex


【解决方案1】:

试试这样的:

"<hello> a b c </hello> <world> x y z </world>".replace(/\s*(<\/?.*?\/?>)\s*/g, "$1")

打印:

"<hello>a b c</hello><world>x y z</world>"

解释:

\s* - 标签前有 0 或 n 个空格

(&lt;\/?.*?\/?&gt;) - 标记,&lt;...&gt;&lt;/...&gt;&lt;.../&gt;,捕获

\s* - 标签后有 0 或 n 个空格

捕获的标签被放回字符串减去未捕获的匹配空格

【讨论】:

    【解决方案2】:

    用两步替换

    代码示例:

    x = `<hello> 
    a b c </hello> <world>
     x y z 
     </world>`;
    x = x.replace(/>\s*/g, '>');
    x = x.replace(/\s*</g, '<');
    console.log(x);
    

    输出:

    <hello>a b c</hello><world>x y z</world>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 2013-02-01
      • 1970-01-01
      • 2015-11-13
      • 1970-01-01
      • 1970-01-01
      • 2020-08-20
      相关资源
      最近更新 更多