开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜