How to create Multiline string in JavaScript?
This article is about how to create multiline string or comment in javascript. To create multil-ine string we will be using template literals in javascript.
In this article, we will learn How to create Multilline String in Javascript.
EMCAScript 6 ( ES6 ) has introduce a new type of literal called template literals.
Template literals (Template strings) have many features like variable / expression interpolation, nesting templates, tagged templates etc. Template literals are delimited with backticks (`), and allows embedded expressions called substitutions.
And among with these features, we also got the Multi-line strings, which helps us to create multi-line string in JavaScript.
In Multi-line strings, any newline characters in the code or source is considered as a part of the template literal.
Create Mutli-line strings in JavaScript
When we use normal strings, we would have to use the following syntax to create multi-line strings in our JavaScript code:
console.log('string text line 1\n' + 'string text line 2'); //OUTPUT // "string text line 1 // string text line 2"
In the above code, in order to create a new line we had to use \n, it create a new line.
However, now using the template literals, we can write multi-line like this example below:
console.log(`string text line 1 string text line 2`); //OUTPUT // "string text line 1 // string text line 2"
We just have to write the strings inside the backticks (`) and it will be displayed as multiline.
Related Topics:
Related Posts
Capitalize First Letter of a String - JavaScript
This article is about how to capitalize the first letter of a string using JavaScript.
Check if String starts with a space in JavaScript
Find out whether a string starts with a space or not using regex test method, string match method and startsWith method in JavaScript.
JavaScript - Detect if a string contains any space
FInd out how to detect if a string contains any white space using regex test() method and string indexOf() method in Javascript.
Split a String into chunks of N character into an array in JavaScript
Find out how to split String into Substrings by length of N characters in JavaScript using split(), match() and substr() methods.
