In this article, we are given a multiline string and the task is to replace line breaks with <br> tag.
Example:
Input: `Geeks for Geeks isĀ a computer science portalĀ where people study computer science` Output: "Geeks for Geeks is <br> a computer science portal <br> where people study computer science"
To achieve this we have the following methods :
Method 1: Using Regex, in this example, we are creating a paragraph and a button and on clicking the button we are changing (Adding the <br>)the text of the paragraph.
We are using the String.replace() method of regex to replace the new line with <br>. The String.replace() is an inbuilt method in JavaScript that is used to replace a part of the given string with another string or a regular expression. The original string will remain unchanged.
Example 1: This example shows the use of string.replace() method to replace the new line with <br>.
HTML
< p id = "para" ></ p > Ā Ā < button onClick = "myFunc()" >Change</ button > < script > Ā Ā Ā Ā let str = `Geeks for Geeks isĀ Ā Ā Ā Ā Ā Ā Ā a computer science portalĀ Ā Ā Ā Ā Ā Ā Ā where people study computer science`; Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā let para = document.getElementById("para"); Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā para.innerHTML = str; Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā function myFunc() { Ā Ā Ā Ā Ā Ā // Replace the \n with < br > Ā Ā Ā Ā Ā Ā str = str.replace(/(?:\r\n|\r|\n)/g, "< br >"); Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // Update the value of paragraph Ā Ā Ā Ā Ā Ā para.innerHTML = str; Ā Ā Ā Ā } </ script > |
Output:
Method 2: Using split() and join(), in this method, we split the string from the delimiter ā\nā which returns an array of substrings, and then we join the Array using the join method and pass <br /> so that every joining contains <br />.
Example 2: In this example, we will use the javascript split() and join() method to replace the new line with <br>
HTML
< p id = "para" ></ p > < button onClick = "myFunc()" >Change</ button > < script > Ā Ā Ā Ā let str = `Geeks for Geeks isĀ Ā Ā Ā Ā Ā Ā Ā a computer science portalĀ Ā Ā Ā Ā Ā Ā Ā where people study computer science`; Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā let para = document.getElementById("para"); Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā para.innerHTML = str; Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā function myFunc() { Ā Ā Ā Ā Ā Ā // Replace the \n with < br > Ā Ā Ā Ā Ā Ā str = str.split("\n").join("< br />"); Ā Ā Ā Ā Ā Ā // Update the value of paragraph Ā Ā Ā Ā Ā Ā para.innerHTML = str; Ā Ā Ā Ā } </ script > |
Output: