GitsD
GitsD

Reputation: 668

How to replace p tag to br using javascript

How would I replace this:

<p class='abc'>blah blah</p> afdads

With this:

blah blah <br/>

Using (vanilla?) JavaScript?

Thanks!

Updated Content

$content = $_REQUEST['content'];
$content = preg_replace('/<p[^>]*>/', '', $content); // Remove the start <p> or <p attr="">
$content = preg_replace('/</p>/', '<br />', $content); // Replace the end
echo $content; // Output content without P tags

I would something like this...hope this time you mates have got my question.

Thankyou

Upvotes: 1

Views: 23254

Answers (4)

jaycode
jaycode

Reputation: 2958

Thank you for posting this question, you're a lifesaver, GitsD.

I replaced your php function to javascript and it worked!

content = content.replace(/<p[^>]*>/g, '').replace(/<\/p>/g, '<br />');

content would now replaced p tags with '' and /p tags with br

Upvotes: 13

Tamzin Blake
Tamzin Blake

Reputation: 2594

I'm afraid your question isn't well-specified. Assuming you want to do that to all p tags with that class, and you're working in a web browser environment:

var paras = document.getElementsByTagName('p')
for (var i = 0; i < paras.length; ) {
  if (paras[i].className.match(/\babc\b/)) {
    var h = paras[i].innerHTML
      , b = document.createElement('br')
      , t = document.createTextNode(h)
      , p = paras[i].parentNode
    p.replaceChild(b, paras[i])
    p.insertBefore(t, b)
  }
  else {
    i++
  }
}

Upvotes: 3

Daniel Cassidy
Daniel Cassidy

Reputation: 25607

If you actually meant JavaScript and not PHP, this would do it:

var ps = document.getElementsByTagName('p');
while (ps.length) {
    var p = ps[0];
    while (p.firstChild) {
        p.parentNode.insertBefore(p.firstChild, p);
    }
    p.parentNode.insertBefore(document.createElement('br'), p);
    p.parentNode.removeChild(p);
}

This works because the NodeList returned by getElementsByTagName is ‘live’, meaning that when we remove a p node from the document, it also gets removed from the list.

Upvotes: 1

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

You could do (if you talk about strings)

var str = "<p class='abc'>blah blah</p> afdads";

str = str.replace("<p class='abc'>", "");
str = str.replace("</p> afdads", " <br/>");
//str = "blah blah <br/>"

Upvotes: 3

Related Questions