javascript 用一个 <br> 替换多个 <br>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17061931/
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
Replace multiple <br>'s with only one <br>
提问by user610983
How do I use JavaScript to detect
我如何使用 JavaScript 来检测
<br>
<br>
<br>
to become one
成为一个
<br>
?
?
I tried with:
我试过:
jQuery('body').html().replace(/(\<br\>\r\n){3, }/g,"\n");
but this is not working for me.
但这对我不起作用。
采纳答案by marekful
Simpler:
更简单:
var newText = oldText.replace(/(<br\s*\/?>){3,}/gi, '<br>');
var newText = oldText.replace(/(<br\s*\/?>){3,}/gi, '<br>');
This will allow optional tag terminator (/>) and also spaces before tag end (e.g. <br />
or <br >
).
这将允许可选的标签终止符 (/>) 以及标签结束前的空格(例如<br />
或<br >
)。
回答by
CSS Solution
CSS 解决方案
If you want to disable the effect of multiple <br>
on the page, you can do it by CSS without using JavaScript:
如果你想<br>
在页面上禁用multiple的效果,你可以通过CSS来实现,而无需使用JavaScript:
br + br { display: none; }
- Check the jsFiddle demo.
- 检查jsFiddle 演示。
However, this method is ideal when you are working with tags, something like this:
但是,当您使用标签时,此方法是理想的,如下所示:
<div>Text</div><br /><br /><br />
<div>Text</div><br /><br /><br />
<div>Text</div><br /><br /><br />
In other cases, like this:
在其他情况下,像这样:
Hello World<br /> <br />
Hello World<br /> <br />
Hello World<br /> <br />
It will fail(as CSS passes text nodes). Instead, use a JavaScript solution.
它会失败(因为 CSS 传递文本节点)。相反,请使用 JavaScript 解决方案。
JavaScript Solution
JavaScript 解决方案
// It's better to wait for document ready instead of window.onload().
window.onload = function () {
// Get all `br` tags, defined needed variables
var br = document.getElementsByTagName('br'),
l = br.length,
i = 0,
nextelem, elemname, include;
// Loop through tags
for (i; i < l - 1; i++) {
// This flag indentify we should hide the next element or not
include = false;
// Getting next element
nextelem = br[i].nextSibling;
// Getting element name
elemname = nextelem.nodeName.toLowerCase();
// If element name is `br`, set the flag as true.
if (elemname == 'br') {
include = true;
}
// If element name is `#text`, we face text node
else if (elemname == '#text') {
// If text node is only white space, we must pass it.
// This is because of something like this: `<br /> <br />`
if (! nextelem.data.replace(/\s+/g, '').length) {
nextelem = br[i+1];
include = true;
}
}
// If the element is flagged as true, hide it
if (include) {
nextelem.style.display = 'none';
}
}
};
- Check the jsFiddle demo.
- 检查jsFiddle 演示。
回答by Kaz
What is the point of sending HTML, which is in a form that you don't want, to the client browser and making it run JavaScriptcode to clean it up? This looks like a bad design.
将您不想要的 HTML 格式发送到客户端浏览器并使其运行JavaScript代码以对其进行清理有什么意义?这看起来是一个糟糕的设计。
How about fixing all your static HTML, and HTML generation, so that these superfluous <br>
elements do not occur in the first place?
如何修复所有静态 HTML 和 HTML 生成,以便<br>
首先不会出现这些多余的元素?
If you use JavaScript to modify the document object, do so for dynamic effects that cannot be achieved in any other way.
如果您使用 JavaScript 修改文档对象,请这样做以获得其他方式无法实现的动态效果。
回答by P.P. Koszta
This solution is jQuery + DOM only, does not manipulate HTML as string, works with text nodes, ignores whitespace only text nodes:
此解决方案仅适用于 jQuery + DOM,不将 HTML 作为字符串进行操作,适用于文本节点,仅忽略空白文本节点:
$('br').each(function () {
const {nodeName} = this;
let node = this;
while (node = node.previousSibling) {
if (node.nodeType !== Node.TEXT_NODE || node.nodeValue.trim() !== '') {
break;
};
}
if (node && node !== this && node.nodeName === nodeName) {
$(node).remove();
}
});
回答by Steve Bennett
Wouldn't something like this be the right approach:
这样的事情不会是正确的方法:
$("br~br").remove()
EDIT: No, it's wrong, because its definition of "contiguous" is too loose, as per BoltClock.
编辑:不,这是错误的,因为根据 BoltClock,它对“连续”的定义太松散了。
回答by Blake Stevenson
A lot of the other answers to this question will only replace up to certain amount of elements, or use complex loops. I came up with a simple regex that can be used to replace anynumber of <br>
tags with a single tag. This works with multiple instances of multiple tags in a string.
这个问题的许多其他答案只会替换一定数量的元素,或者使用复杂的循环。我想出了一个简单的正则表达式,可用于用单个标签替换任意数量的<br>
标签。这适用于字符串中多个标签的多个实例。
/(<br>*)+/g
To implement this in JavaScript, you can use the String.replace
method:
要在 JavaScript 中实现这一点,您可以使用以下String.replace
方法:
myString.replace(/(<br>*)+/g, "<br/>");
To replace multiple <br/>
tags, add a /
to the regex:
要替换多个<br/>
标签,请/
在正则表达式中添加一个:
/(<br\/>*)+/g
回答by Jair Reina
I would go with this:
我会这样做:
$('body').html($('body').html().replace(/<br\W?\?>(\W?(<br\W?\?>)+)+/g,"<br>"));
However, after reading the comments in another post here I do consider that you should try to avoid doing this in case you can correct it in the back end.
但是,在阅读了此处另一篇文章中的评论后,我确实认为您应该尽量避免这样做,以防您可以在后端进行更正。