To assign a multiline string literal to a variable in JavaScript, you can use template literals (enclosed with backticks `
), which support multiline strings without special formatting. Here are the methods and considerations:
1. Using Template Literals (ES6+)
Template literals preserve line breaks and indentation exactly as written:
const multilineStr = `This is a
multiline string
using backticks.`;
console.log(multilineStr);
// Output:
// This is a
// multiline string
// using backticks.
2. Handling Indentation
To avoid unwanted leading/trailing whitespace:
const cleanStr = `
This line has no leading spaces.
This line is indented in the string.
`.trim(); // Removes leading/trailing whitespace
console.log(cleanStr);
// Output:
// This line has no leading spaces.
// This line is indented in the string.
3. Legacy Approach (Pre-ES6)
For environments that don’t support ES6, use string concatenation with +
and \n
:
var oldMultilineStr = "This is a\n" +
"multiline string\n" +
"using concatenation.";
4. Escaping Backticks
Include backticks in the string by escaping them with \
:
const withBacktick = `This string contains a \` backtick.`;
Key Notes
- Whitespace: Indentation in the code becomes part of the string. Use
.trim()
to remove leading/trailing spaces. - Browser Support: Template literals work in modern browsers (ES6+) but not in IE.
- Readability: Template literals are cleaner than concatenation for multiline text.
Example with Dynamic Content
Template literals also support embedded expressions (${...}
):
const user = "Alice";
const message = `Hello ${user},
Your account balance is $100.
Thank you!`;
console.log(message);
// Output:
// Hello Alice,
// Your account balance is $100.
// Thank you!
Summary
Method | Example | Use Case |
---|---|---|
Template Literals | `Line 1\nLine 2` | Modern code, readability, dynamic content |
String Concatenation | "Line 1\n" + "Line 2" | Legacy environments |
.trim() | \n Text\n .trim() | Remove leading/trailing whitespace |
Preferred Method: Use template literals for clarity and ease.