New line in browser (IE, Opera, Firefox)

I did a webpage before to store some message. The point is I need to count the total characters, including new line character.

In IE and Opera new line character will consume 2 spaces because they use the characters “\r\n”, however if the message is saved under Firefox 2 or Firefox 3, the new line character only consume 1 space, this will create a problem because the next program reading those message need the new line characters in format “\r\n”, means at least 2 spaces for that.

After some test I found that Firefox will use a single character “\n” to represent a new line character, it is different with IE and Opera which using “\r\n” as new line character.

This findings shows that message saved under firefox will has a little different because of that “\n”. In order to sync the saved output, I add some extra code to handle this situation for Firefox browser only:

// Handle Firefox save data issue
// (Firefox only use line-feed as new line)

if (browser == "Netscape") {
msg = msg.replace(/\n/g,"\r\n");

Above code will detect if there is a Firefox browser, and do some trick on new line character, replace “\n” to “\r\n” when save the message. So that the output will looks same in IE and Opera browser, and has no issue for next program to read.

I never test for Google Chrome and Safari, anybody who interest on that can test at your own. Do let me know your test result, 🙂

~~~ * ~~~ * ~~~

Update 14/Oct/2009

Thanks for yair comment. Basically this post is talking about line feed inside <textarea>, if you would like to show a line feed in website, <br /> would be your choice. 🙂

UrlEncode in Javascript? Call me encodeURI

Last time I facing issue on encode url string in javascript, and I guess there maybe a built-in function to do that.

I did a search on Google using keyword “UrlEncode javascript equivalent”, then found this article, it solve my problem.

However there are some different between encodeURI() and encodeURIComponent(), below is the difference pick from w3schools.

Tips and Notes

Note: The encodeURI() function encodes special characters, with the exception of:
, / ? : @ & = + $ #. Use the encodeURIComponent() function to encode these characters.

Tip: Use the decodeURI() function to decode URIs encoded with encodeURI().