【问题标题】:Convert html raw text into inline text (remove spaces) Regex Javascript将 html 原始文本转换为内联文本(删除空格)正则表达式 Javascript
【发布时间】:2021-01-11 07:20:37
【问题描述】:

我尝试将 html 文本转换为内联文本,标签之间或标签内的文本之间没有空格,但文本不会丢失空格。查看下面的代码以获取更多信息。

This is my html from which I want to remove the whitespaces

const html = `
 <div>
   <div>
     <span>This is a text</span>
     <div>
       Another text
     </div>
   </div>
 </div>
`;

我尝试“编写”下面的正则表达式,但它是错误的。我现在也删除标签。我尝试了不同的正则表达式方法,但我无法创建(或理解)正则表达式代码。

我愿意:

console.log(html.replace(/\>(\s+?)\</g,''))

输出:

<divdivspan>This is a text</spandiv>
       Another text
     </div/div/div>

我想:

console.log(html.replace('(regex)', ''))
output: <div><div><span>This is a text</span><div>Another text</div></div></div>

【问题讨论】:

标签: javascript regex


【解决方案1】:

不知道为什么要这样做,但这有效

我剪切并粘贴了您的 HTML,还必须添加 \r 和\n

const html = `<!--aaaaa--><div>
   <div>
     <span>This is a text</span>
     <div><!-- asda asdasd asdasdasd -->
       Another text
     </div><!-- comment 
     over two lines -->
   </div>
 </div>`
 
 const noSpaceOrComments = html
   .replace(/<!--[\s\S]*?-->/gm,"") // comments
   .replace(/^(\s+)?|(\s+)?$/gm,"") // leading and trailing whitespace
   .replace(/\r|\n/g,"") // trailing newlines
 
 console.log(noSpaceOrComments)

【讨论】:

  • 非常感谢,你救了我。我的公司使用旧的节点 html 解析器,并且当 html raw 没有内联无法识别 html 时出现错误。在我们重写之前,我会尝试“解决”损坏的应用程序。
  • 我需要你最后一次的帮助。我也需要匹配 html cmets,正则表达式 '\' 但我无法匹配空格。 '' 匹配,但 ``` ``` 只是片刻......
  • 对不起,我没有解释正确的误解。我想替换不匹配的 cmets,我不想打开新线程。我不知道如何从 regex101.com 分享只是截图prnt.sc/wkstms
  • 左边有一个链接可以点击。你还没有解释你想让 cmets 做什么
  • 很抱歉,我想创建一个“方法”来删除 cmets,只需替换为空字符串即可。在上面的链接中,我编写了一个正则表达式,女巫需要匹配 cmets,但匹配内联 cmets。我尝试添加有关空格和新行的引用,但我无法理解正则表达式。当我有时间的时候,我需要阅读并了解更多关于正则表达式的信息。 regex101 链接:regex101.com/r/VVv141/1 感谢您的耐心和帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-01
  • 2016-05-08
  • 1970-01-01
  • 2011-01-21
  • 2021-10-22
  • 1970-01-01
相关资源
最近更新 更多