如何使用javascript中的正则表达式在html标记中获取内容,包括标记?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用javascript中的正则表达式在html标记中获取内容,包括标记?相关的知识,希望对你有一定的参考价值。

我下面有文字-

how  much  production  in  batu

现在此文本显示为一系列html标签。基本上每个单词都用特定的spanstyle包裹在class中。这是它的样子

'<span style="">how &nbsp;</span><span style="">much &nbsp;</span><span class="pink-highlight">production &nbsp;</span><span style="">in &nbsp;</span><span class="yellow-highlight">batu</span>'

现在我要从此html字符串中得到两件事:样式或类以及跨度内的内容(没有&nbsp;

因此,我希望从字符串中获取以下信息的array

[["", "how"], ["", "much"], ["pink-highlight", "production"], ["", "in"], ["yellow-highlight", "batu"]]

现在可以使用regex轻松完成。但是我对regex并不熟悉。我能想到的模式

<span>(.*?)</span>

但是它只会发现span内部的内容,在这种情况下甚至无法使用,因为每个span都有一个style标签或一个类。

那么,在这种情况下,什么regex最适用于获得期望的结果?

答案

使用正则表达式可能无法匹配HTML。将其解析为HTML并获取数据非常容易。

var html = '<span style="">how &nbsp;</span><span style="">much &nbsp;</span><span class="pink-highlight">production &nbsp;</span><span style="">in &nbsp;</span><span class="yellow-highlight">batu</span>'

var temp = document.createElement('div')
temp.innerHTML = html
var data = Array.from(temp.querySelectorAll('span'))
  .map(span =>
    ([
      span.getAttribute("style") || span.getAttribute("class") || '', span.textContent.trim()
    ])
  )
console.log(data)
另一答案

我将提供一个简单的正则表达式。实际上,我只添加了2个选项。

(<span>(.*?)</span>)|(<span style=".*?">(.*?)</span>)|(<span class=".*?">(.*?)</span>)

以上是关于如何使用javascript中的正则表达式在html标记中获取内容,包括标记?的主要内容,如果未能解决你的问题,请参考以下文章

mongoose 查询 $in 不区分大小写的正则表达式不起作用

如何通过正则表达式收集 HTML 链接中的文本?

Mongoose 验证:必需:false,验证:正则表达式,空值问题

Mongoose 验证:必需:false,验证:正则表达式,空值问题

负前瞻正则表达式

正则表达式