Wednesday, February 24, 2010

Convert or Replace carriage-return/New-Line/line-break/End-of-line characters in JavaScript

Even though this might seem simple, you might come across cross browser issues and other issues based on the pre-processing of the string from different programming languages. Let's forget all those and keep the below concepts in mind.

From JavaScript's perspective, the string can have "\r\n" as a whole OR "\r" only OR "\n" only. In most of the scenario, the string variable will be having \n at a minimum. Thus, considering all three possibilities, what we can do is this.

var newString = oldString.replace(/\n/g, "< br >").replace(/\r/g, "");

Note that the above sample code is using a Regular Expression match using "g", so that all the occurences will get replaced. Now, you can change the above logic as per your needs.

More Information:
For those who tend to confuse with all these characters, here is what it is in a nutshell. As an example, this is what gets stored in the variable when user press [ENTER] in the keyboard. The following are their representation as special characters.

\n New Line/Line feed
\r Carriage Return

Generally, UNIX systems will have "\n", "\r" will be used in MAC and a comibnation of "\r\n" will be used in Windows OS.

1 comment:

Anonymous said...

Thanks for posting this! Very useful :)

Post a Comment