Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery / Regex: remove all p tags [duplicate]

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.

like image 241
user2571510 Avatar asked Nov 28 '22 15:11

user2571510


2 Answers

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

updated regex

like image 59
Anatoliy Gusarov Avatar answered Dec 06 '22 10:12

Anatoliy Gusarov


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>
like image 25
Tomalak Avatar answered Dec 06 '22 08:12

Tomalak