JavaScript – Multi-line Strings
To write multi-line strings in JavaScript, there are two methods.
- Use string concatenation operator
+
. - Use backslash at the end of each line, in a string, except for the last line.
Examples
An example to define a multi-line string using +
operator is
</>
Copy
var str = 'Eat one apple, ' +
'one banana, ' +
'and one orange.';
An example to define a multi-line string using backslash at the end of each line is
</>
Copy
var str = 'Eat one apple, \
one banana, \
and one orange.';
In the following example, we define a multi-line string using +
operator, and display this string in a div.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<div id="output"></div>
<script>
var str = 'Eat one apple, ' +
'one banana, ' +
'and one orange.';
document.getElementById('output').innerHTML = str;
</script>
</body>
</html>
In the following example, we define a multi-line string using backslashes at the end of each lines in the string, and display this string in a div.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<div id="output"></div>
<script>
var str = 'Eat one apple, \
one banana, \
and one orange.';
document.getElementById('output').innerHTML = str;
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned how to write multi-line strings in JavaScript, in different ways, with examples.