JQuery: how to remove variable number of p-tags from string

I have a string that contains the content of an HTML variable. A string can contain one or more p tags, which can 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 one.

I tried the following first, but of course it only works if I have the entire line wrapped in a paragraph and it won't cover if there are classes or other attributes in the paragraphs:

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

      

Edit: Here's an example, but the number of p-tags can change and there can't be any 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"

      

Thanks so much for any help on this, Tim.

+3


source to share


5 answers


You can use regex for this . It only removes 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 want to remove all tags, you can use /(<([^>]+)>)/ig

as a regex instead.

+2


source


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



This is the opposite of wrapping in that it removes the parent of the selector. The tag p

is the parent of the content elements, the content selection before the unwrapping expands the tags p

. jsFiddle

+4


source


Try the following:

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

      

+1


source


If I understood correctly and you want the p tags to be removed, but the content should still be as simple as:

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

      

+1


source


You can also use replaceWith - jsFiddle example readable and working with parent / child tags

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

      

+1


source







All Articles