Search code examples
javascriptstringhtmlcontenteditable

using a div contentEditable innerText and innerHTML neither have newlines to and from database


I'm using a div for people to enter text and then I tried saving

div.innerText

and

div.innerHTML

to my database but when I bring it back from the database and put it back into the div all of the carriage returns or newlines are gone

innerHTML to database

a

b

c

    //in database like this  <div>a</div><div></div><div>b</div><div></div><div>c</div>

innerText to database

a
a
a
a
a
a
    //how it stored in database  aaaaaa

if you could tell me how to handle this situation I would appreciate it greatly thank you for your time


Solution

  • div.innerHTML creates an HTML output of your new lines using <div> containers. Therefore the line breaks will be "replaced".

    div.innerText uses the "invisible" character \n or \r\n to mark new lines and it is possible that they are not shown in your database. You can however replace them by <br> tags to see if they are there.

    document.getElementById("output").addEventListener("click", function() {
      console.log("HTML:");
      console.log(document.getElementById("text").innerHTML);
      console.log("Text:");
      var text = document.getElementById("text").innerText;
      console.log(text.replace(/(?:\r\n|\r|\n)/g, '<br>'));
    });
    #text {
      background-color:#FAFAFA;
      border: red solid 1px;
      height:150px;
      width: 200px;
    }
    <button id="output">
      Show in console
    </button>
    
    <div id="text" contenteditable>
    
    </div>

    console.log(text.replace(/(?:\r\n|\r|\n)/g, '<br>')); replaces all different kinds of possible new lines into <br> tags.