I\'ve got a JSP page with a piece of Javascript validation code which limits to a certain amount of characters on submit. I\'m using a so I can
Do you particularly care which line-endings are used? Why not just make the Java convert "\r\n" to "\n"? (Note that "\r\n" is the Windows style; "\n" is the Unix style.)
Alternatively, do the reverse when checking the length within the JavaScript.
Are you limiting it to 2000 chars so it fits inside an nvarchar(2000) column in a database? Otherwise maybe just allow a 2% overrun to be flexible on the Java side.
And Java should be using Unicode UTF16 to represent Strings. That /r
must have got in there somewhere else, maybe a conversion in the web browser when submitting? Have you tried different browsers? On different platforms? You might just have to strip out the /r
s.
This isn't really a JavaScript (or Java) problem - both layers report an accurate length for the string they are dealing with. The problem in your case is that the string gets transformed during the HTTP transmission.
If you absolutely must ensure that the string doesn't exceed a certain length, you can mimic this transformation on the client by replacing every instance of "\n" with "\n\r" - but only for length verification purposes:
textarea.value.replace(/\n/g, "\r\n").length