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.
source to share
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);
If you want to remove all tags, you can use /(<([^>]+)>)/ig
as a regex instead.
source to share
You can also use replaceWith - jsFiddle example readable and working with parent / child tags
$('p').replaceWith($('p').text())
source to share