Hello
I'm playing around with reading the value.length of textarea's. Everything works fine, as long you're not using linebreaks.. and there it starts..
First of all, my environment detailsOS: Windows XP SP3
Browser: IE 7.0.5730.13 (standards compliant rendering mode), Firefox 3.5.5
Doctype: XHTML-Strict
Some factsOS:
Windows is using by default 2 bytes for a linebreak
Unix is using by default 1 byte for a linebreak
Mac is using by default 1 byte for a linebreak
http://en.wikipedia.org/wiki/Newline JavaScript:
As far as I know JavaScript is using only 1 byte for a linebreak (\n). Doesn't matter if it's running on a Windows/Unix/Mac OS.
HTTP/1.1 protocol:
HTTP/1.1 uses 2 bytes for a linebreak, if I understand correctly..
"HTTP/1.1 defines the sequence CR LF as the end-of-line marker for all protocol elements except the entity-body..."
http://www.rfc-editor.org/rfc/rfc2616.txt TestsI have a form and within, there is a textarea element. I write the following text into it (without the start and end lines):
-- start
a
b
c
-- end
The following happens..
- $textarea = $("textarea");
- alert($textarea.val().length); // 1. Will alert 5
- alert($textarea[0].value.length); // 2. Will alert 7
After my "investigations" I realized, this behavior is caused by the difference between how many bytes are used for a linebreak.
On a linux system with any browser the 2. statement will also return 5 (because unix uses only 1 byte for a linebreak).
But if I submit the form to the server, and check the length of the data of the textarea, it will tell me the string is 7 chars long (because http/1.1 uses 2 bytes per linebreak I guess).
Unfortunately I was not able to test it on a Mac.
ConclusionI think it would be nice if the length property would return the correct value.. especially if you want to make some validation on a form/textarea.
Since http/1.1 protocol always converts 1 byte linebreaks to 2 bytes, we could assume that the webserver is always receiving 2 bytes for a linebreak. So also 2 bytes would be written to the database ( I hope I'm not telling bullshit here! :)
My solution at the moment is the following function:
- if (String.prototype.realLength == undefined) {
- String.prototype.realLength = function() {
- var regex
- if (regexp.test(this)) {
- do { matchCount++; } while (regexp.exec(this));
- return this.replace(/\n|\r/g, "").length + matchCount * 2;
- }
- return this.length;
- };
- }
Maybe there are better/different solutions, or maybe I made a mistake during my "investigations".
Please let me know..
Cheers, delijah