javascript jQuery / Regex:删除所有 p 标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19821951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery / Regex: remove all p tags
提问by user2571510
I am new to Regex and hope someone can help me with the following:
我是 Regex 的新手,希望有人可以帮助我解决以下问题:
I have a long string that is saved as a variable. The string contains plain text and HTML tags, incl. p tags.
我有一个保存为变量的长字符串。该字符串包含纯文本和 HTML 标签,包括。p 标签。
How can I use Regex to remove all p tags from my string including classes and IDs on the p tags but without losing the text inside ? The string variable can contain one, multiple or no p tags but always contains at least some text.
如何使用正则表达式从我的字符串中删除所有 p 标签,包括 p 标签上的类和 ID,但不会丢失里面的文本?字符串变量可以包含一个、多个或不包含 p 标签,但始终至少包含一些文本。
Example:How it looks now:
示例:现在的样子:
var str = Some awesome text with a <p class='myClass'>new paragraph</p> and more text.
How it should look:
它应该是什么样子:
var str = Some awesome text with a new paragraph and more text.
Thanks for any help with this, Tim.
感谢您对此的任何帮助,蒂姆。
回答by Anatoliy Gusarov
result = str.replace(/(<p[^>]+?>|<p>|<\/p>)/img, "");
updated regex
更新正则表达式
回答by Tomalak
Based on this answerthat's easy enough to do in jQuery.
基于这个答案,在 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>