jQuery / Regex: remove all p tags [duplicate]

拈花ヽ惹草 提交于 2019-12-08 07:51:40

问题


I am new to Regex and hope someone can help me with the following:

I have a long string that is saved as a variable. The string contains plain text and HTML tags, incl. p tags.

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.

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.


回答1:


result = str.replace(/(<p[^>]+?>|<p>|<\/p>)/img, "");

updated regex




回答2:


Based on this answer that's easy enough to do in jQuery.

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

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

var output = $temp.html();


来源:https://stackoverflow.com/questions/19821951/jquery-regex-remove-all-p-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!