【问题标题】:Is there any way I can remove \n from inner html inside a div?有什么办法可以从 div 内的内部 html 中删除 \n 吗?
【发布时间】:2019-10-26 13:59:41
【问题描述】:

我想删除 div 元素中的 \n,但似乎没有任何效果。

我尝试使用 html(String)text(String) 方法,但 \n 仍然存在

<div class="line number1 index1 alt1">
 \n
 1
 \n
</div>
<div class="line number2 index2 alt2">
\n
 2
 \n
</div>
<div class="line number3 index3 alt1">
 \n
 3
 \n
</div>

有什么办法可以做到吗?

谢谢

【问题讨论】:

  • 请张贴minimal reproducible example - 并减少您的示例输入的大小 - 您不需要演示同样的事情 6 次。
  • 展示您如何看待问题的一些观点。看到页面中的\n了吗?
  • 页面中未显示的\n,但它导致的div 的高度比预期的要大。(\n 显示在调试器中)

标签: java html jsoup


【解决方案1】:

您可以通过使用简单的正则表达式来使用String.replaceAll() 方法吗?

htmlString = htmlString.replaceAll("\\n","");

【讨论】:

  • 不应该是这样的吗? htmlString = htmlString.replaceAll("\n","");
  • 不,因为你也需要逃避它,对吧?
  • 我试过 eleme.html(eleme.html().replaceAll("\\n",""));但 \n 仍然存在
  • 然后尝试简单的\n
  • 它似乎既不适用于简单的 \n 也不适用于 \\n
【解决方案2】:

只需将此脚本添加到您的 html 文件中。它将从带有class="line" 的每个元素中获取一个文本,计算其中发生了多少\n 以及删除它之后。

脚本:

String.prototype.count = function(s1) { 

    return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
}


$('.line').each(function(){

    let happens, i; 
    happens = $(this).text().count('\\n');

    for (i = 0; i < happens; i++) {
        $(this).text($(this).text().replace('\\n',''));
    }
});  

【讨论】:

  • Jsoup 不会运行任何 JavaScript,所以这并不能解决问题。
【解决方案3】:

有一个开源库 MgntUtils(由我编写)具有 TextUtils.formatStringToPreserveIndentationForHtml 它所做的事情之一 - 它将所有 '\n' 替换为 '&lt;br&gt;' 这可能对您有用。这是该方法的 javadoc 的链接:formatStringToPreserveIndentationForHtml。该库可以取为Maven artifact 或取自Github(包括源代码和Javadoc)。这是关于图书馆文章的链接:MgntUtils Open Source Java library

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-01
    • 2011-05-28
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 2020-07-13
    相关资源
    最近更新 更多