Textarea elements modify carriage returns (\r)

String comparison before and after will always fail

·

2 min read

Textarea elements modify carriage returns (\r)

Recently, I was working on a simple text editor that allows a user to enter multiple lines of text into a <textarea> element. When the user has finished editing, they can submit the text and it will be sent off to our backend API, which will do some backend magic and come back with a personalized version of the text embedded within an image.

In order to prevent unnecessary calls to the API, I implemented a simple check to make sure that the user had actually changed the text by simply comparing the textarea.value to the original string.

WTF!!!

I could not get this simple check to work.

Try clicking the Populate button followed by the Get & Compare button below

Logging out the values seemed to provide a visible difference between the strings.

extAreaElement.value: This is the first line
This is the second line

stringWithReturn: This is the first line
This is the second line

This really really confused me.

After some digging around, I stumbled on the suggestion of logging out the string values using JSON.stringify(). I don't remember ever logging out known strings with JSON.stringify().

console.log(JSON.stringify(textAreaElement.value))
// This is the first line\nThis is the second line

console.log(JSON.stringify(stringWithReturn))
// This is the first line\rThis is the second line

And here we have the problem. When you retrieve the value of a <textarea> element in JavaScript, you will get the text with normalized line breaks, represented as newline characters \n.

If you use an API that requires carriage returns \r. Be careful with unintended modifications to the text when these are used in the browser. Any further processing or checking will need to convert the newlines \n back to carriage returns \r using something like the following.

textAreaElement.value.replace(/\n/g, '\r') === stringWithReturn;