Create multiline strings in JavaScript
This post will discuss how to create multiline strings in JavaScript.
1. Using String Concatenation
You can use the concatenation operator + to show the string on multiple lines. This can be done using either double or single quotes.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
const str = 'This is a\n' + 'multiline string\n' + 'using\n' + 'string concatenation'; console.log(str); /* Output: This is a multiline string using string concatenation */ |
2. Backslash in string
Instead of concatenating multiple strings, you can use the backslash (\) escape character to escape the newline.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
const str = 'This is a\n\ multiline string\n\ using\n\ backslash'; console.log(str); /* Output: This is a multiline string using backslash */ |
3. Using template literals
Template literals is a recent addition to JavaScript which allows multiline strings and support features like string interpolation. Template literals are enclosed by the backtick character. The string, as well as newlines in the source, will be preserved.
This makes the code more readable and eliminates the need for concatenation or escaping. The following program demonstrates how to create multiline strings using the template literals.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
const str = `This is a multiline string using backticks`; console.log(str); /* Output: This is a multiline string using backticks */ |
That’s all about creating multi-line strings in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)