【问题标题】:How to get the plain text from summernote editor?如何从summernote编辑器获取纯文本?
【发布时间】:2015-06-14 18:52:02
【问题描述】:

例如,这是我输入的:

sdf
42342
xxcv

.code() 将其转换为sdf<br>42342<br>xxcv

或者别的:

[{"_type":"ServerOperation","operationType":"ANNOUNCE"}]

变成

<span class="message_content">[{"_type":"ServerOperation","operationType":"ANNOUNCE"}]</span>

如何获取纯文本/纯文本?

【问题讨论】:

    标签: jquery html css summernote


    【解决方案1】:

    试试这个:

    var plainText = $($("#summernote").code()).text()
    

    编辑: 在较新的版本中,您需要使用它:

    var plainText = $($("#summernote").summernote("code")).text()
    

    【讨论】:

    • 强大,并避免在 hmtl 上使用正则表达式。这一定是公认的答案!
    • 您的答案可能会返回一个空字符串。 $('').html($("#summernote").summernote("code")).text() 更好!
    【解决方案2】:

    您可以在.code() 之后应用问题JavaScript: How to strip HTML tags from string? 的前两个答案之一来剥离标签。

    ReactiveRaven 的回答(保持一行)对我来说很好:

    cleanText = $("#summernote").code().replace(/<\/?[^>]+(>|$)/g, "");
    

    例如,[{"_type":"ServerOperation","operationType":"ANNOUNCE"}]:

    • $("#summernote").code() 返回

      &lt;p&gt;[{"_type":"ServerOperation","operationType":"ANNOUNCE"}]&lt;br&gt;&lt;/p&gt;

    • $("#summernote").code().replace(/&lt;\/?[^&gt;]+(&gt;|$)/g, "") 返回

      [{"_type":"ServerOperation","operationType":"ANNOUNCE"}]

      没有任何标签。


    如果您想保留回车,可以在应用链接问题中指定的解决方案之前将&lt;/p&gt;&lt;br&gt; 替换为\n

    $("#summernote").code()
                    .replace(/<\/p>/gi, "\n")
                    .replace(/<br\/?>/gi, "\n")
                    .replace(/<\/?[^>]+(>|$)/g, "");
    

    【讨论】:

    • 是的,同时我用php的striptag解决了它
    【解决方案3】:

    我需要检查 textarea 是否有任何内容。这已经成功了:

    当前的summernote版本(8):

    $($("#summernote").summernote('code').replace(/&nbsp;|<br>/g, ' ')).text().trim() == ''
    

    在我的旧版本中:

    $($("#summernote").code().replace(/&nbsp;|<br>/g, ' ')).text().trim() == ''
    

    【讨论】:

    • 这很有用,但不能按原样工作。我必须将“.code()”更改为“.summernote('code')”才能正常工作。
    • 在当前版本中,似乎正如@AustinBest 所说。在这里:hub.readthedocs.io/en/stable/assets/global/plugins/… 我在旧版本中找到了它。我相信 Summernote API 已经改变了,但我不知道具体的版本。
    【解决方案4】:

    你可以用这个

       var code = $("#editor").code();
    var text = code.replace(/<p>/gi, " ");
    var plainText= $("<div />").html(text).text();
    

    【讨论】:

    • div 包装内容非常重要,就像您在这里所做的$("&lt;div /&gt;").html(text).text(); 一样。因为如果你 Summernote 的内容包含一些纯文本并且你没有将整个内容包装在一个 HTML 标记(如 div)中,那么 jQuery 将通过一个错误说它不是预期的。
    【解决方案5】:

    较新的版本

    var contents = $('#summernote').summernote('code');
    var plainText = $("<p>" + contents+ "</p>").text();
    

    添加虚拟标签

    解决了格式缺失问题。

    【讨论】:

      【解决方案6】:

      试试这个:)

      $('#summernote').summernote ('code', '<b> hello world </ b>');
      

      【讨论】:

      • 问题是如何获取文本以及插入文本
      猜你喜欢
      • 2018-07-06
      • 2016-04-09
      • 2011-03-02
      • 2015-09-08
      • 2014-03-22
      • 2011-11-15
      • 2017-10-18
      • 2014-08-27
      • 1970-01-01
      相关资源
      最近更新 更多