简体   繁体   中英

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

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.

You can substitute <textarea> element for <div> with contenteditable attribute set. Encode, decode .value of textarea using encodeURIComponent() , decodeURIComponent() or format data as JSON utilizing JSON.stringify() , JSON.parse()

 var button = document.querySelector("button") var textarea = document.querySelector("textarea"); button.onclick = function() { var value = textarea.value console.log(encodeURIComponent(value) , decodeURIComponent(value) , JSON.stringify(value) , JSON.parse(JSON.stringify(value)) ); } 
 textarea { border: 1px solid navy; width: 300px; height: 200px; } You can use 
 <button>click</button><br> <textarea></textarea> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM