How to Replace the Carriage Return With a Line Break Tag in JavaScript
- 1). Prepare your text. If you already have text to work with, or are using your script to read it from a file, store it within a string variable. You can use the following syntax, creating a string variable with some characters and a carriage return in it:
var theText = "Here is some text \r with multiple lines \r in it.";
If your text has been read from a text file, there will probably not be spaces around the carriage return characters, they are just included here for clarity. - 2). Define the characters that you want to replace. The replace function uses a regular expression defining which characters are to be found and eliminated within the string. The following code demonstrates defining the carriage return character as a string variable:
var replaceChars = "\r";
This variable is ready to be passed to the replace function. The carriage return is a special character in JavaScript, which is why it is preceded by the backslash. - 3). Define the string that you want to replace the carriage return with. The replace function will be passed by the replacement text as a parameter. Using the following code, create a new variable indicating the string that you want to replace the carriage returns with:
var replacementString = "<br/>";
This string variable indicates the HTML markup required for a line break within a Web page, so if the text is displayed within the browser, it will be split accurately across multiple lines. - 4). Carry out the replace function on your string. Using the following code, replace the carriage returns with line breaks in your code:
var newText = theText.replace(replaceChars, replacementString);
This code carries out the replace function in the original text string, defining the characters to replace and the string to replace them with. The function returns a new string with the replacement completed. - 5). Output your new string to the browser to test it. If you are replacing carriage returns with HTML line breaks, you can write the new text to the Web page. The following code demonstrates writing new HTML content into an element with "content" as its ID attribute:
document.getElementById("content").innerHTML = newText;
Save your file and open your Web page in a browser to test it.
Source...