【问题标题】:How to replace <br/> tag with the \n(new line) in jquery如何在 jquery 中用 \n(new line) 替换 <br/> 标签
【发布时间】:2012-08-08 06:12:11
【问题描述】:

我使用此代码 sn-ps 将 &lt;br/&gt; 标记替换为 jquery 中的“\n”(新行)。但它没有工作

  $("#UserTextArea").html(data.projectDescription).replace(/\<br\>/g, "\n");

但它不起作用,这是为什么?

【问题讨论】:

    标签: javascript jquery jsp-tags


    【解决方案1】:

    .replace() 不会更改内容本身。它返回一个新字符串,所以如果你想使用这个新字符串,你必须把.replace()的返回值放在某个地方。

    如果您的目标是 &lt;br\&gt;,您可能还需要通过转义 \ 并将其设为可选来修复您的正则表达式。

    仅供参考,在 HTML 中 \n 没有任何作用,因此如果您只是想删除 #UserTextArea 中的所有 &lt;br&gt; 标记,您可以使用 DOM 解析器来执行此操作:

    $("#UserTextArea br").remove();
    

    或者,如果您只想将带有 &lt;br&gt; 标记的字符串替换为可用于其他用途的变量,您可以这样做:

    var str = $("#UserTextArea").html().replace(/\<br\\?>/g, "\n");
    

    或者,您可以从data.projectDescription 中删除&lt;br&gt; 并将其作为HTML 分配给#UserTextArea,您可以这样做:

    $("#UserTextArea").html(data.projectDescription..replace(/\<br\\?>/g, "\n"));
    

    【讨论】:

    • 我认为换行符确实意味着 pre 标记中的某些内容?
    【解决方案2】:

    $("#UserTextArea").html(data.projectDescription.replace(/\&lt;br[\/]*\&gt;/g, "\n"));

    【讨论】:

    • 它不是工作伙伴。我也使用 $("#UserTextArea").html(data.projectDescription.replace("
      ", "\n"));它也不起作用
    • data.projectDescription的内容是什么?
    【解决方案3】:
    $('#UserTextArea').html(data.projectDescription.replace(/\<br\s*\>/g, '\n'));
    

    或者,搜索和替换元素的内部 HTML:

    var $element = $('#UserTextArea');
    var html = $element.html();
    $element.html(html.replace(/\<br\s*\>/g, '\n'));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-05
      • 1970-01-01
      • 2017-04-30
      • 1970-01-01
      • 1970-01-01
      • 2012-09-22
      • 1970-01-01
      相关资源
      最近更新 更多