Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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/

like image 324
Naftali Avatar asked Apr 05 '12 15:04

Naftali


People also ask

Does carriage return count as a character?

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? Here's your answer with evidence: whatwg.org/specs/web-apps/current-work/multipage/…

Is Crlf a single character?

These are two characters: \r is carriage return; \n is line feed.

What is carriage return character in JavaScript?

CR = Carriage Return ( \r , 0x0D in hexadecimal, 13 in decimal) — moves the cursor to the beginning of the line without advancing to the next line.

Do new lines count as characters?

Yes, each line break, space and carriage return adds to your character count.


1 Answers

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.

like image 136
Pointy Avatar answered Sep 21 '22 14:09

Pointy