How to add line breaks in JavaScript alert

By Saruque Ahamed Mollick

In this JavaScript tutorial, we gonna learn how to add line breaks in JavaScript alert. The alert method is very much useful to us. But sometimes we need to have multiple lines or you can say more than one line in an alert message of a browser.
JavaScript can help web developers, especially front-end developers in a tremendous manner just because of having so many features. But for security reasons, modern browsers are cutting down some of the features. ( like alert before leaving a webpage with a custom message )

In the simple alert method, we can add line breaks easily.

You may also read,

Alert Before Leaving A Web Page Using JavaScript jQuery

How to find the Keycode in JavaScript ( Core JavaScript no jQuery )



Add line breaks in JavaScript alert

Adding line breaks in JavaScript is very much easy. Because It is just like same as other popular languages. Most of the programmers start with C. Even in C we use the same sign to give a line break.

The below line will create an alert message with a line break.

alert('This is first line\nThis is second line');

The ‘\n’ is used to create a line break.

\n

Line breaks in JavaScript alert message example

Here is an easy example where if you click on the button you will get a message with a line break.

<!DOCTYPE html>
<html>
<head>
  <title>Add line break in JavaScript Alert</title>
</head>
<body>
  
  <script>
    function my_function(){
      alert('This is first line\nThis is second line');
    }
  </script>
  <button onclick="my_function()">Hello</button>

</body>
</html>

3D Photo/Image Gallery (on space) Using HTML5 CSS JS

Leave a Reply

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