javascript 如何使用javascript将p标签替换为br

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6373650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:26:17  来源:igfitidea点击:

How to replace p tag to br using javascript

javascriptreplacepreg-replace

提问by GitsD

How would I replace this:

我将如何替换这个:

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

With this:

有了这个:

blah blah <br/>

Using (vanilla?) JavaScript?

使用(香草?)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

谢谢

回答by jaycode

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

感谢您发布这个问题,您是一个救星,GitsD。

I replaced your php function to javascript and it worked!

我将您的 php 函数替换为 javascript 并且它起作用了!

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

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

内容现在将用 '' 替换 p 标签,用 br 替换 /p 标签

回答by Nicola Peluchetti

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

回答by Tamzin Blake

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:

恐怕你的问题没有明确说明。假设您想对具有该类的所有 p 标签执行此操作,并且您正在 Web 浏览器环境中工作:

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

回答by Daniel Cassidy

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

如果您实际上是指JavaScript而不是 PHP,则可以这样做:

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 NodeListreturned by getElementsByTagNameis ‘live', meaning that when we remove a pnode from the document, it also gets removed from the list.

这是有效的,因为NodeList返回的getElementsByTagName是'live',这意味着当我们p从文档中删除一个节点时,它也会从列表中删除。