&quo"/> &quo">
Home > Article > Web Front-end > How to replace newlines using JavaScript?
In this tutorial, we will learn how to replace all newlines in JavaScript code using the
tag. There are various ways to replace all newlines using
tokens. Some methods are given below-
In this method, we use String.replace() method to convert plain text into Replace all newline characters with
tokens. RegEx here refers to the regular expression we wrote in the string.replace() method.
The following is the use of the replace() method-
sentence.replace(/(?:\r|\r|)/g, "<br>");
HereThe sentence is a string with a newline character, and the replacement() method One parameter is a regular expression.
Step 1 - Define a string with newlines and display it.
Step 2 strong> - Apply the replace() method to the string defined above. Use the above syntax to apply the replacement method.
Step 3 - Display the string obtained in step 2. All newlines are replaced with
.
We can use the code given below to replace all newlines with ## using regular expressions # mark.
<script> let sentence = `Javascript is a dynamic computer programming language for web. Javascript can update and change both HTML and CSS`; let br = document.getElementById("br"); br.innerHTML = sentence; function linebreak() { // Replace the line break with <br> sentence = sentence.replace(/(?:\r|\r|)/g, "<br>"); // Update the value of paragraph br.innerHTML = sentence; } </script>In the above code, string.replace() method checks all 3 types of newline characters i.e. \r, and \r and uses \g tags and replace them with
tags.
so that every connection contains
.
sentence.split("").join("<br />");Here
The sentence is with a newline (
) string, we need to replace it with.
Step 1 - Define a string with newlines and display it.
Step 2 - Apply the split() and join() methods to the string defined above. Use the above syntax to apply the replacement method.
Step 3 - Display the string obtained in step 2. All newlines are replaced with .
<script> let sentence = `Javascript is a dynamic computer programming language for web. Javascript can update and change both HTML and CSS`; let br = document.getElementById("br"); br.innerHTML = sentence; function linebreak() { // Replace the line break with <br> sentence = sentence.split("").join("<br />"); // Update the value of paragraph br.innerHTML = sentence; } </script>
The above is the detailed content of How to replace newlines using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!