简体   繁体   中英

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

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

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/>"

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++
  }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM