javascript replace line break

How to Replace Line Breaks With
in JavaScript

Websites and applications often require you to accept input string in one format and convert it into another format. For example, you may receive a plain string with line breaks and may need to replace them with <br> tags, if you want to display it as HTML. In this article, we will learn how to replace line breaks with <br> in JavaScript.

How to Replace Line Breaks With <Br> in JavaScript

It is very easy to replace line breaks with <br> in JavaScript. You can easily do this using replace() function. Here is the syntax of replace() function

string.replace(old_substring, new_substring);

In the above function, we need to provide old substring or regular expression for the substring, that you want to replace, as first argument, and the new substring as the second argument. If you use just a plain substring as first argument, replace() function will replace only the first occurrence of the substring. If you want to replace all occurrences of substring, you need to use a regular expression for the substring to be replaced.

Let us say you have the following plain string with line breaks, as shown below.

var str = "Hello World.

     Good Morning."

Let us say you want to replace the above string with the following.

"Hello World.<br/> Good Morning."

You can easily do this using the following command.

str = str.replace(/(?:\r\n|\r|\n)/g, '<br>');
str = str.replace(/(?:\r\n|\r|\n)/g, '<br/>');

In the above code, the first argument of replace() function is a regular expression to match all types of line breaks, irrespective of OS (Linux, Windows, Mac). Some OS uses \n as line breaks, some use \r\n and some use \r. This regular expression will replace all of those. If you want to replace only some of them like \n but not \r then you can customize the above expression as per your requirement. Also, we have used ?: at the beginning of regular expression to specify a non-capturing group of regex, that is, it will not be saved in memory for future reference, making it more efficient. You can omit it if you want to.

In this article, we have learnt how to replace line breaks with <br> tag in JavaScript.

Also read:

How to Detect When User Leaves Web Page
How to Generate PDF from HTML Using JavaScript
How to Auto Resize IFrame Based on Content
How to Count Substring Occurrence in String in JS
How to Convert Comma Separated String into JS Array

Leave a Reply

Your email address will not be published.