How to get the plain text from summernote editor?

You could apply one of the top two answers for the question JavaScript: How to strip HTML tags from string?, after the .code() to strip the tags.

ReactiveRaven's answer (to keep it to one line) works fine for me:

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

For example, With [{"_type":"ServerOperation","operationType":"ANNOUNCE"}]:

  • $("#summernote").code() returns

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

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

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

    without any tags.


And if you want to preserve the carriage return, you could replace </p> and <br> for a \n before applying the solution specified on the linked question:

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

Just try this:

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

EDIT: In newer versions you need use this instead:

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

I needed to check if the textarea had any content. This have done the trick:

Current summernote version (8):

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

In my older version:

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

you can use this

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