Display new line in javascript
In JavaScript, you can display a new line in several ways:
-
Using the
\n
character:console.log("Hello\nWorld");
This will output:
Hello World
The
\n
character is an escape sequence that represents a new line. -
Using the
<br>
tag:document.write("Hello<br>World");
This will output:
Hello World
The
<br>
tag is an HTML element that represents a line break. -
Using the
document.createElement
method:var br = document.createElement("br"); document.write("Hello" + br.outerHTML + "World");
This will output:
Hello World
The
document.createElement
method creates a new<br>
element, and theouterHTML
property returns the HTML representation of the element. -
Using the
String.prototype.replace
method:var str = "Hello"; str = str.replace(/\n/g, "<br>"); document.write(str + "World");
This will output:
Hello World
The
String.prototype.replace
method replaces all occurrences of the\n
character with the<br>
tag. -
Using the
String.prototype.split
method:var str = "Hello\nWorld"; var arr = str.split("\n"); document.write(arr[0] + "<br>" + arr[1]);
This will output:
Hello World
The
String.prototype.split
method splits the string into an array of substrings, using the\n
character as the separator.