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.
result = str.replace(/(<p[^>]+?>|<p>|<\/p>)/img, "");
updated regex
Based on this answer that's easy enough to do in 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With