This tutorial is a part of our initiative at Flexiple, to write short curated tutorials around often used or interesting concepts.
- Breaking string using an Escape sequence
- New line using Template literals
- HTML Break Element
\n, but in a few older macs
\r is used. The implementation of escape sequences is quite straightforward. I have added a snippet below.
let flexiple = "Hire the top 1% freelance talent"; let new_flexiple = "Hire the \ntop 1% \nfreelance talent"; console.log(flexiple); //Output: "Hire the top 1% freelance talent" console.log(new_flexiple); //Output: "Hire the //top 1% //freelance talent"
Template literals sound quite fancy, but underneath the jargon, they are just string literals that allow embedded expressions. This makes it easy to use multi-line strings. We do not enclose template literals with single or double quotes but rather with backtick (
let flexiple = "Hire the \ntop 1% \nfreelance talent"; let new_flexiple = `Hire the top 1% freelance talent`; console.log(flexiple); //Output: "Hire the //top 1% //freelance talent" console.log(new_flexiple); //Output: "Hire the //top 1% //freelance talent"
In both cases, the same output is returned. but as you can see Template Literals make it quite simple to write multi-line strings.
Adding HTML line break elements to your string is another method I have seen being used quite often. Though break elements must be used where the division of a line must be significant since this method is quite common we look at it as well.
<html> <body> <p id="newline"></p> <script> let flexiple = "Hire the" + "<br>" + "top 1% "+ "<br>" + "freelance talent"; document.getElementById("newline").innerHTML = flexiple; </script> </body> </html>
Note: Remember to use the .innerHTML and not .innerText as you would with other text content.
Do let me know your thoughts/ queries in the comment section below.