In this article, we will provide a complete guide on how to create a Multiline string in JavaScript. The multiline are useful for writing paragraph content, or a block of text formatting.
There are several approaches to create a multiline string in JavaScript. We will explain each approaches in detail with a description and complete code examples.
Approach 1: Using Template Literals (ES6)
Template literals, introduced in ECMAScript 2015 (ES6), provide a convenient way to create multiline strings in JavaScript. You can enclose the string within backticks (` `) and freely include line breaks without the need for escape characters.
const multilineString = `This is a multiline string in JavaScript`; console.log(multilineString);
Approach 2: Concatenating Strings with the Plus Operator
While not as elegant as template literals, you can still create multiline strings by concatenating multiple string literals using the plus (+) operator. Ensure each string is enclosed within single or double quotes, and use the plus operator to concatenate them.
const multilineString = "This is a " + "multiline " + "string in JavaScript"; console.log(multilineString);
Approach 3: Using Array Joining
Another approach is to define an array of strings, each representing a line of the multiline string, and then join them using the join()
method with the desired line break character.
const multilineArray = [ "This is a", "multiline", "string in JavaScript" ]; const multilineString = multilineArray.join("\n"); console.log(multilineString);
Approach 4: Escaping Line Breaks with Backslash
You can also use the backslash () character to escape line breaks within a string. This approach can be useful in situations where template literals or concatenation are not feasible.
const multilineString = "This is a \ multiline \ string in JavaScript"; console.log(multilineString);
Approach 5: Using String.fromCharCode() Method
For scenarios where maintaining readability is crucial, you can utilize the String.fromCharCode()
method to insert line breaks using the newline character’s Unicode value.
const multilineString = "This is a" + String.fromCharCode(10) + "multiline" + String.fromCharCode(10) + "string in JavaScript"; console.log(multilineString);