javascript - 在 JS 中使用 RegExp 将任何仅包含空格的 html 标签替换为其空格(数量相同)

标签 javascript regex

我想在 JS 中使用 RegExp 来替换其中仅包含空格(' ' )的任何 html 标签及其 html 编码等效  .

例如:

替换

'<strong> &nbsp; &nbsp; </strong>' => '&nbsp; &nbsp;'

另一个例子,

替换:

'<strong>&nbsp; &nbsp; &nbsp;</strong> => '&nbsp; &nbsp; &nbsp;'

最佳答案

您可以使用如下正则表达式:

str = str.replace(/<(\w+)>((?:&nbsp;|\s)+)<\/\1>/g, '$2');

说明:

<(\w+)>          matches the start tag and captures the name
(                group to capture the content
(?:&nbsp;|\s)+   matches &nbsp; or whitespace, one or more times
)                ends group
<\/\1>           matches the end tag with the name of the start tag

匹配项被替换为$2,即第二组中的值,即标签内的内容。

关于javascript - 在 JS 中使用 RegExp 将任何仅包含空格的 html 标签替换为其空格(数量相同),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33303134/

相关文章:

Javascript 日期 : what is the best way to deal with Daylight Savings Time?

javascript - prestashop-使用 ajax onclick 创建新表单

javascript - 在 node.js 中计算 Content-length header 的正确方法是什么

.net - 原子量化组与量化原子组的含义相同吗?

c++ - C/C++ 中的正则表达式

c# - 捕获正则表达式 C# 中的特定或组

javascript - angularjs ng-options嵌套json数据

javascript - 文档片段如何工作?

regex - Linux grep 表达式停止匹配,直到找到一个 windows 回车符

regex - 您如何发现 spark 数据框中列格式的异常?