Search code examples
jqueryhtmlcsssummernote

How to get the plain text from summernote editor?


for example, this is what I entered:

sdf
42342
xxcv

.code() converts it to sdf<br>42342<br>xxcv

or another thing:

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

becames

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

how to get the pure / plain text?


Solution

  • 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, "");