javascripthtmltextarea

Text written to textarea is altered when read back - CR is removed


I have a <textarea> element in an HTML page. I am writing data to it with Javascript and want to check later if the user has altered the text at all. However if the data contains any carriage returns they appear to be silently removed, so comparing the text read from the textarea with a copy of what should be there fails.

JSFiddle here demonstrating the problem:

https://jsfiddle.net/5j4erkst/

Is this expected behaviour?


Solution

  • Yes, this is the expected behavior. The standard says:

    the value used in the value IDL attribute ... is normalized so that line breaks use U+000A LINE FEED (LF) characters.

    This differs from the value submitted to the server:

    It is normalized so that line breaks use U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pairs.

    Update in 2024

    The current standard says:

    the value, as used in form submission and other processing models in this specification. It is normalized as for the API value

    and the API value is normalized like:

    replace every U+000D CR U+000A LF code point pair with a single U+000A LF code point, and then replace every remaining U+000D CR code point with a U+000A LF code point

    Hence a line break in the submitted textarea value is now represented with a single \n.