Creating multiline strings in JavaScript
JavaScript Template literals (Template strings) allow you to create a string that spans multiple lines.
const mString = `First line -
Second Line -
Third Line`;
Output:
First line - Second Line - Third Line
Template literals
Template literals (Template strings) are literals delimited with backtick (`) characters, allowing for multi-line strings.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Multiline String</h2>
<p id="demo"></p>
<script>
const mString = `First line -
Second Line -
Third Line`;
document.getElementById("demo").innerHTML = mString;
</script>
</body>
</html>
Using JavaScript join()
JavaScript join() method allow you to create a string that spans multiple lines. The join() method returns an array as a string. This method does not change the original array. Also, any separator can be specified. The default is comma (,).
var mString =
['<div id="mID">',
'First Line<br />',
'Second Line<br />',
'Third Line<br />',
'<a href="#Ref">MyLink</a>',
'</div>'
].join('\n');

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Multiline String</h2>
<p id="demo1"></p>
<script>
var mString =
['<div id="mID">',
'First Line<br />',
'Second Line<br />',
'Third Line<br />',
'<a href="#Ref">MyLink</a>',
'</div>'
].join('\n');
document.getElementById("demo1").innerHTML = mString;
</script>
</body>
</html>
Using JavaScript + Operator
JavaScript + Operator allow you to create a string that spans multiple lines.
var mString = "First Line - "
+ "Second Line - "
+ "Third Line";

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Multiline String</h2>
<p id="demo3"></p>
<script>
var mString = "First Line - "
+ "Second Line - "
+ "Third Line";
document.getElementById("demo3").innerHTML = mString;
</script>
</body>
</html>
Related Topics
- JavaScript Popup Boxes
- Opening a new window in JavaScript
- How to Create Drop-Down Lists in JavaScript
- How do I include a JavaScript file in another JavaScript file?
- Print the content of a Div using JavaScript/jQuery
- How to get the current URL using JavaScript ?
- How to Detect a Mobile Device with JavaScript/jQuery
- How to validate an email address in JavaScript
- JavaScript Array Iteration
- How to Remove a Specific Item from an Array in JavaScript
- What is JavaScript closures?
- How To Remove a Property from a JavaScript Object
- How to get selected value from Dropdown list in JavaScript
- How do I get the current date in JavaScript?
- How to Open URL in New Tab | JavaScript
- How to delay/wait/Sleep in code execution | JavaScript
- How to round to at most 2 decimal places | JavaScript
- How to convert string to boolean | JavaScript
- How to check undefined in JavaScript?
- How To Copy to Clipboard | JavaScript
- How to encode a URL using JavaScript?
- How to force Input field to enter numbers only | JavaScript
- How to Check for an Empty String in JavaScript?