How to add a new line in JavaScript string

String Manipulation is very easy to understand but it is very difficult to master it.

Adding a new line in JavaScript string

We will see different ways in which we can add a new line in the Javascript console and in the DOM.

Using Escape Sequence

The newline character in JavaScript and many other computer languages is backslash n (\n).To insert a new line, just insert the \n character where you want the linebreak in a string.

Example:

const test_str = "Codespeedy,\nSolution to your tech problems”
console.log(test_str);

Output:

Codespeedy,
Solution to your tech problems

Here, you should be mindful of the whitespace around the newline character as it can impact the characters after the line break.

Using Template literals

You can also make use of template literals to use multi-lines. It is easier to add extra lines. Strings wrapped in backticks(`) instead of single quotation(‘) or double(“)  quotations are known as template literals. It also preserves whitespaces including new lines.

const test_str =`Hello, there,
how are you`
console.log(test_str);

Output:

Hello, there,
how are you

For DOM output

Here we need to make use of<br>element if we want to add a new line on our webpage. For this, we need to manipulate the DOM element. We cannot create DOM output by utilizing an escape sequence (\n) or template literals (`).

Example:

<html> 
<body> 
<p id="sent"></p> 
<script> 

let str = "Here you" + "<br>" + "will"+ "<br>" + "see the change"; 

document.getElementById("sent").innerHTML = str; 

</script> 
</body> 
</html>

Output:

add a new line in JavaScript string

Also read: How to remove new line character in JavaScript (\n)

Leave a Reply

Your email address will not be published. Required fields are marked *