javascriptangulartextareainnerhtmlinnertext

Javascript innerText adds two \n for every carriage return key user pressed


Im my Angular project i have a textarea from which the innerHTML is read and characters count remaining shown to user

The from the same textarea i read text via innerText and send to server with length to store in DB.

Here innerHTML is : "hi<div><br></div><div>k</div><div><br></div><div>gh</div>" - Length 9
     innerText is : "hi\n\n\nk\n\n\ngh"  - Length 11

This is an issue when user enters maximum characters in textarea and when reading via innerText it exceeds that max limit when more carriage returns are used in paragraph.

I need both length to be in sync.


Solution

  • This is happening because your HTML includes two line breaks between each section.

    Using <div>...</div> separates content onto a new line. Additionally, the <br> within the <div> creates a second new line.

    It seems like your input is literally:

    hi
    
    k
    
    gh
    

    And if this was represented in a single line it would be literally: hi\n\nk\n\ngh because you have two breaks between each line.

    If you want some alignment between the HTML and text formats, you will want to:

    or