Remove first <p> tag and last </p> string tag with jQuery

Asked

Viewed 53 times

3

I have a string with several HTML tags. I want to remove only the first tag <p> and the last tag </p> of this string. I found solutions that remove all tags but these do not serve.

Example:

<p> 
   Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
  <p> Nullam feugiat, turpis at pulvinar vulputate</p> 
  Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
</p>

You should stay:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
<p> Nullam feugiat, turpis at pulvinar vulputate</p> 
 Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
  • I don’t think there’s much to do but manipulate the string directly. The tags are right at the beginning/end of the string, such as <p>alguma coisa</p> or is it something more mixed <div><div><p>algumacoisa</p></div></div>?

  • Always at the beginning and at the end

  • Amanda did not understand well, want to remove only and only <p> of the beginning and </p> end. Or you want to remove the first/last <p> in full: <p>REMOVER</p><p>NÂO REMOVER</p><p>REMOVER</p>

  • I edited the question to show how it should look

1 answer

3


I think that solves!

var s = "<p>uma coisa<p>outra coisa</p></p>";
s = s.substring(s.indexOf("<p>") + 3, s.lastIndexOf("</p>"));

Now if the text does not always contain the tag <p>, then you’ll need to do some additional checks.

  • Perfect!! It’s just what I need, thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.