New line in string javascript
In JavaScript, there are a few ways to create a new line in a string:
-
Using the newline character (
\n
):const myString = "Hello\nWorld!";
This will create a new line between "Hello" and "World!".
-
Using the escape sequence (
\r\n
):const myString = "Hello\r\nWorld!";
This will also create a new line between "Hello" and "World!".
-
Using the HTML
<br>
tag:const myString = "Hello<br>World!";
This will create a new line between "Hello" and "World!" using an HTML
<br>
tag. -
Using the
replace()
method:const myString = "Hello"; myString = myString.replace(/\n/g, "<br>");
This will replace all newline characters (
\n
) with<br>
tags. -
Using the
join()
method:const myArray = ["Hello", "World!"]; const myString = myArray.join("<br>");
This will join the elements of the array with
<br>
tags, creating a new line between each element.
Note that the first two methods (\n
and \r\n
) will work in most browsers and environments, but may not work in all cases (e.g., in some older browsers or in certain text editors). The other methods may be more reliable, but may also have different effects depending on the context in which the string is used.