Why does Javascript only count carriage returns as one character when it is two?

carriage-return, dom, javascript

Solution

For reasons unknown, jQuery always converts all newlines in the value of a `<textarea>` to a single character. That is, if the browser gives it `\r\n` for a newline, jQuery makes sure it's just `\n` in the return value of `.val()`. (Actually the reason probably isn't "unknown"; it's probably to normalize the results across browsers, because IE reports newlines as being 2 characters long.)

Chrome and Firefox both count the length of `<textarea>` tags the same way for the purposes of "maxlength".

However, the HTTP spec insists that newlines be represented as `\r\n`. Thus, jQuery, webkit, and Firefox all get this wrong. When the field is posted, webkit and Firefox correctly add the newlines!

The upshot is that "maxlength" on `<textarea>` tags is pretty much useless if your server-side code really has a fixed maximum size for a field value.

Edit This is still an issue in 2015 - at least on Chrome 45.0.2454 and IE 11.0.9600.

Problem

This is an offshoot of this question: Chrome counts characters wrong in textarea with maxlength attribute In that question it was found that Javascript counts carriage returns are one character when in fact it is two (`\r\n`), why is that? Test Fiddle: http://jsfiddle.net/maniator/E527z/

Original source

Related problems