How Do You Use Multi-Line String Variables in JavaScript?

Problem scenario
You want to present multiple lines in an "alert" message in JavaScript. How do you have new lines with text in JavaScript?

Possible Solution #1 (less preferred)
Use syntax like this:

var y  = `
  line1
  line2
  line3
`;

Possible Solution #2 (preferred)

var z = [
  line1,  
  line2, 
  line3  
].join("\n");

You could use this stand-alone file multiline.html:

<!DOCTYPE html>
<html>
<body>

<h2>This demonstrates a multi-line variable in JavaScript</h2>


<p id="demo"></p>

<script>

line1 = "aaa"
line2 = "bbb"
line3 = "ccc"

var z = [
  line1,  
  line2, 
  line3  
].join("\n");


alert(z)

</script> 

</body>
</html>

Leave a comment

Your email address will not be published. Required fields are marked *