Let's check out all the different ways along with example.
The escape sequence
To create new line using escape sequence \n, we just have to type it at the end of the line.
const normalLine = "hello coder. Learn about programming languages here." const newLine = "hello coder.\nLearn about programming languages here." console.log(normalLine) console.log(newLine)
// normalLine hello coder. Learn about programming languages here. //newLine hello coder. Learn about programming languages here.
DO NOT add space at the end of
\n. It will add the space at the beginning of the new line.
Template Literals are string literals that provide easy ways to interpolate expressions in a string. These are literals delimited with back ticks (
const str = `hello coder. Learn about programming languages here. Happy Coding` console.log(str)
hello coder. Learn about programming languages here. Happy Coding
To print out new line in a web-page we have to manipulate the DOM using
<br > HTML element .
<br > element in a string and render it to our web-page.
Example of < br > in HTML code:
<body> <p> This is a webpage. <br /> This is a HTML element </p> </body>
This a webpage. This is a HTML element
<br > element inside the string.
<body> <div id="myText"></div> <script> let element = document.getElementById("myText"); element.innerHTML = "This is a webpage. <br /> This is a HTML element"; </script> </body>
This script code will render the output with a newline with
<br/> in the HTML page inside the
<div id="myText"> This is a webpage <br /> This is a HTML element </div>