Create new line statement in javascript
In JavaScript, there are a few ways to create a new line:
-
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:console.log("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:const br = document.createElement("br"); console.log("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.split
method:const str = "Hello World"; const arr = str.split(" "); console.log(arr.join("\n"));
This will output:
Hello World
The
split
method splits the string into an array of substrings, and thejoin
method concatenates the array elements with a new line character (\n
). -
Using the
String.prototype.replace
method:const str = "Hello World"; const newStr = str.replace(/ /g, "\n"); console.log(newStr);
This will output:
Hello World
The
replace
method replaces all occurrences of a space character (`) with a new line character (
\n`).
Note that the \n
character is not a literal new line, but rather an escape sequence that represents a new line. If you want to create a literal new line, you can use the String.prototype.split
method or the String.prototype.replace
method with a regular expression.