[英]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? 使用(香草?)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. 感谢您发布此问题,您是救生者,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标签
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:
假设您要对该类的所有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++
}
}
If you actually meant JavaScript and 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 NodeList
returned by getElementsByTagName
is 'live', meaning that when we remove a p
node from the document, it also gets removed from the list. 之所以有效,是因为
getElementsByTagName
返回的NodeList
是“ live”的,这意味着当我们从文档中删除p
节点时,它也会从列表中删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.