In this article, we will discuss the utilization of the JavaScript string newline character.
What is the JavaScript String Newline Character?
The JavaScript newline character places a line break by adding a new line to the string. For this purpose, the following two approaches can be utilized:
- “\n” character.
- “</br>” tag.
Method 1: Using String Newline “\n” Character in JavaScript
The “\n” is a JavaScript character used to break the string value by placing a line break.
Example
In this example, the “\n” character is used to break the string value twice by placing line breaks:
let a = 'JavaScript\nHi!\n This is Linuxhint';
console.log(a);
</script>
In the above code snippet:
- Firstly, create a variable and assign the stated string value.
- In the string value, the allocated “\n” characters will place line breaks in the string value.
- Finally, display the resultant string value with two-line breaks on the console.
Output
In the above output, it can be seen that the specified string value has been split into new lines.
Method 2: Using String Newline Character With “</br>” Tag in JavaScript
The “</br>” tag is used to place a line break in the HTML code. This tag can also be utilized to break the string value into two or more two lines.
Example
Let’s go through the below code lines:
<script>
let myText = 'This is Paragraph</br>With JavaScript';
document.getElementById('myHeading').innerHTML = myText;
</script>
According to the given code snippet:
- Firstly, include the “<h3>” tag to accumulate the resultant string value as a heading.
- In the JavaScript code, create a variable named “myText” and assign the stated string value.
- In the specified string value, the “</br>” tag indicates that the string content will be displayed in the new line after the placed tag./li>
- Lastly, access the included heading by its “id” using the “getElementById()” method and append the resultant string value in the form of a heading via the “innerHTML” property.
Output
In this output, it is evident that the resultant string value with the line breaks is displayed in the form of a heading.
Conclusion
The “\n” and the “</br>” are the newline characters that place a line break in the HTML and JavaScript codes, respectively. This write-up illustrated the utilization of both characters to place line break(s) in the JavaScript code with the help of examples.