【问题标题】:jQuery / Regex: remove all p tags [duplicate]jQuery / Regex:删除所有 p 标签 [重复]
【发布时间】:2013-11-06 20:17:45
【问题描述】:

我是 Regex 的新手,希望有人可以帮助我解决以下问题:

我有一个保存为变量的长字符串。 该字符串包含纯文本和 HTML 标签,包括。 p 标签。

如何使用正则表达式从我的字符串中删除所有 p 标签,包括 p 标签上的类和 ID,但不会丢失里面的文本? 字符串变量可以包含一个、多个或不包含 p 标签,但始终至少包含一些文本。

示例: 现在的样子:

var str = Some awesome text with a <p class='myClass'>new paragraph</p> and more text.

它应该是什么样子:

var str = Some awesome text with a new paragraph and more text.

感谢您对此提供的任何帮助,蒂姆。

【问题讨论】:

  • 谢谢,但我不认为这是重复的,因为我还需要删除 p 标签上的类和 ID。
  • 好奇:为什么一行文本中间有一个paragraph标签?
  • @Eevee:当文本的某些部分居中或右对齐时会出现p标签。

标签: javascript jquery html regex strip


【解决方案1】:
result = str.replace(/(<p[^>]+?>|<p>|<\/p>)/img, "");

更新的正则表达式

【讨论】:

  • 最好使用另一种方法,它操纵 HTML 而不是用正则表达式到处乱扔它
  • 是的,但是用户想要的正则表达式,为什么不呢?继续!
  • 如果您只需要删除 p 标签,而您只有字符串,那么使用一个正则表达式真的不对吗? jquery也是用regex找元素的,所以你说用regex找元素,然后创建几个对象,然后用几种方法去掉tag,比用一个regex好?
  • 如果有多个

    ,这也会删除第一个

    中的内容。

  • @BennyNeugebauer 谢谢,已更新。
【解决方案2】:

基于this answer,这在 jQuery 中很容易做到。

var str = "Some awesome text with a <p class='myClass'>new <b>paragraph</b></p> and more text.";

var $temp = $("<div>").html(str);
$temp.find("p").each(function() {
  $(this).replaceWith(this.childNodes);
});

var output = $temp.html();

$("#original").html(str);
$("#input").text(str);
$("#output").text(output);
$("#result").html(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="original"></div>
<pre id="input"></pre>
<pre id="output"></pre>
<div id="result"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 2013-04-28
    • 2018-12-11
    • 2020-09-03
    • 2016-12-13
    相关资源
    最近更新 更多