jQuery / Regex: remove all p tags

16,752

Solution 1

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

updated regex

Solution 2

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>
Share:
16,752
user2571510
Author by

user2571510

Updated on June 20, 2022

Comments

  • user2571510
    user2571510 almost 2 years

    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.

  • user2571510
    user2571510 over 10 years
    Thanks for the fast reply - that's exactly what I was looking for !
  • Eevee
    Eevee over 10 years
    better to use the other approach, which manipulates HTML rather than slopping it around with a regex
  • Anatoliy  Gusarov
    Anatoliy Gusarov over 10 years
    yes, but user want's regex, so why not? go ahead!
  • Anatoliy  Gusarov
    Anatoliy Gusarov over 10 years
    if you need to remove just p tag, and you have only string, is it really wrong to use one regex? Jquery uses regex to find elements too, so you say that find element with regex, then create several objects, then use several methods to remove tag is better than use one regex?
  • Vadorequest
    Vadorequest over 9 years
    This also delete the content inside the first <p> if there is more than one <p>.
  • Benny Neugebauer
    Benny Neugebauer about 9 years
    Please check with: result = "<p>Hello World</p>".replace(/(<p[\s\S]+?>|<\/p>)/g, '');. It REMOVES the content inside the <p> tag which is unwanted.
  • Anatoliy  Gusarov
    Anatoliy Gusarov about 9 years
    @BennyNeugebauer thanks, updated.
  • Benny Neugebauer
    Benny Neugebauer about 9 years
    Cool! Now you got my upvote :)