如何从Summernote编辑器获取纯文本?

20

例如,这是我输入的内容:

sdf
42342
xxcv

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

或者另一件事情:

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

becomes

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

如何获取纯文本/无格式文本?

7个回答

39

试试这个:

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

编辑: 在更新的版本中,您需要使用这个替代方法:

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

2
强大的,并避免在HTML上使用正则表达式。这必须是被接受的答案! - Click Ok
$('<textarea />').html($("#summernote").summernote("code")).text()更好! - Rui Wang

22
你可以在问题“JavaScript:如何从字符串中删除HTML标记?”中应用前两个答案之一,在.code()之后去除标记。
ReactiveRaven的答案(仅限一行)对我来说很有效:
cleanText = $("#summernote").code().replace(/<\/?[^>]+(>|$)/g, "");
例如,使用 [{"_type":"ServerOperation","operationType":"ANNOUNCE"}]

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

<p>[{"_type":"ServerOperation","operationType":"ANNOUNCE"}]<br></p>

$("#summernote").code().replace(/<\/?[^>]+(>|$)/g, "") 返回:

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

不带任何标签。


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

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

是的,与此同时我用PHP的striptag解决了它。 - John Smith

5

我需要检查文本区域是否有任何内容。这是一个有效的方法:

当前的Summernote版本(8):

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

在我的旧版本中:

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

2
这很有用,但它不能直接使用。我必须将“.code()”更改为“.summernote('code')”,才能使其正常工作。 - Austin Best
1
在当前版本中,似乎是@AustinBest所说的那样。在这里:https://hub.readthedocs.io/en/stable/assets/global/plugins/bower_components/summernote/README.html#api 我在旧版本中找到了它。我相信summernote API已经发生了变化,但我不知道具体是哪个版本。 - Gli

4

您可以使用这个

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

1
将内容用<div>包裹起来非常重要,就像你在这里所做的 $("<div />").html(text).text();。因为如果summernote的内容包含一些纯文本,并且你没有将整个内容包装在一个HTML标签(如<div>)中,则jQuery会报错。 - ismnoiet

2

较新的版本

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

添加一个虚拟标签

可以解决格式不正确的问题。


1

对于版本0.8.20:

如果您想获取实际文本,而没有Summernote的任何样式(粗体、斜体等)和换行:

$("<div />").html($("#summernote").summernote("code")).text();

如果您想要文本、Summernote的样式和换行符:
$("<textarea />").html($("#summernote").summernote("code")).text();

-2
尝试一下这个 :)
$('#summernote').summernote ('code', '<b> hello world </ b>');

问题是如何获取文本以及关于插入文本的内容。 - Shehzad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接