简体   繁体   中英

How to remove variable number of p tags from a string in jQuery

I have a string that contains variable HTML content. The string can contain one, more or no p tags which may also have classes on them.

What is the best way to remove all p tags from this using jQuery while keeping the HTML content of each of them.

I first tried the following but of course this only works if I have the whole string wrapped in a paragraph and it would not cover if the paragraphs have classes or other attributes on them:

str.substring(3).slice(0, -4);

Edit

Here is an example but the number of p tags can vary and there can also be none at all.

Example before:

<p>Some text <p class="someClass"> Some other text</p> Some more text</p>

Example after:

"Some text Some other text Some more text"

Use Unwrap : $('p').contents().unwrap()

It is the opposite of wrap in that it removes the parents of the selector. The p tags are the parent elements of the content, selecting the content before unwraping will unwrap the p tags. jsFiddle

You could use a regular expression to do this. It only removes the p-tags and leaves all other tags in place.

JavaScript

var string = "<p>this is a test with <p class='bold'>multiple</p> p-tags.</p><span>THIS IS COOL</span>";
var result = string.replace(/<[\/]{0,1}(p)[^><]*>/ig,"");

console.log(result);

FIDDLE

If you'd like to remove all tags, you could use /(<([^>]+)>)/ig instead as regex.

Try the following:

var str = "<p>Test</p>";
var res = str.replace("<p>", "").replace("</p>", "");

如果我理解正确,并且您希望删除 p 标签但内容仍然存在,那么它应该很简单:

str.replace('<p>', '').replace('</p>', '');

您还可以使用 replaceWith - jsFiddle Example ,可读并与父/子标签一起使用

$('p').replaceWith($('p').text())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM