Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to Line Breaks to JavaScript Alert?
To add line breaks to JavaScript alerts, you can use several escape sequences. The most common and cross-browser compatible approach is using for new lines.
Common Line Break Characters
JavaScript supports multiple line break characters:
-
- Line feed (most common, works across browsers) -
\r- Carriage return + line feed (Windows style) -
\r- Carriage return (older Mac style)
Using
(Recommended)
<!DOCTYPE html>
<html>
<body>
<script>
function displayAlert() {
var msg = "First line<br>";
msg += "Second line<br>";
msg += "Third line";
alert(msg);
}
</script>
<button onclick="displayAlert()">Show Alert with Line Breaks</button>
</body>
</html>
Using \r
<!DOCTYPE html>
<html>
<body>
<script>
function displayMultiLineAlert() {
var newLine = "\r<br>";
var msg = "Showing how to add line break.";
msg += newLine;
msg += "Line Break can be easily added in JavaScript.";
msg += newLine;
msg += "Simply Easy Learning";
msg += newLine;
msg += "TutorialsPoint.com";
alert(msg);
}
</script>
<button onclick="displayMultiLineAlert()">Click for Multi-line Alert</button>
</body>
</html>
Template Literals Method
ES6 template literals provide a cleaner way to create multi-line strings:
<!DOCTYPE html>
<html>
<body>
<script>
function templateLiteralAlert() {
var msg = `Welcome to TutorialsPoint!
This is the second line.
This is the third line.
Happy Learning!`;
alert(msg);
}
</script>
<button onclick="templateLiteralAlert()">Template Literal Alert</button>
</body>
</html>
Comparison
| Method | Syntax | Browser Support | Readability |
|---|---|---|---|
|
Simple | All browsers | Good |
\r |
Verbose | All browsers | Fair |
| Template literals | Clean | Modern browsers | Excellent |
Conclusion
Use for simple line breaks in alerts. For modern applications, template literals offer the cleanest syntax for multi-line strings.
Advertisements
