Sometimes we need to show more than one line in an alert box so that we can convey our message in a great form.
These are the following methods:
Table of Content
Method 1: Using “\n” escape character
In this approach, we are using the “\n” escape character for printing the new line in the alert box. we are adding “\n” in the middle of the text that is needed to show in the alert box.
Example: This example shows the implementation of the above-explained approach.
<!DOCTYPE html> < html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport"
content = "width=device-width, initial-scale=1.0" >
< title >Document</ title >
</ head >
< body >
< h1 style = "color:green;" >
GeeksforGeeks
</ h1 >
< p >
Click on the button to pop
alert box with added new line.
</ p >
< button onclick = "gfg_Run()" >
click here
</ button >
< script >
let text =
"This is line 1\nThis is line 2";
function gfg_Run() {
alert(text);
}
</ script >
</ body >
</ html >
|
Output:
Method 2: Using “\r” escape character
In this approach, we are using the “\r” escape character for printing the new line in the alert box. we are adding “\r” in the middle of the text that is needed to show in the alert box.
Example: This example shows the implementation of the above-explained approach.
<!DOCTYPE html> < html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport"
content = "width=device-width, initial-scale=1.0" >
< title >Document</ title >
</ head >
< body >
< h1 style = "color:green;" >
GeeksforGeeks
</ h1 >
< p >
Click on the button to pop
alert box with added new line.
</ p >
< button onclick = "gfg_Run()" >
click here
</ button >
< script >
let text =
"This is line 1\rThis is line 2";
function gfg_Run() {
alert(text);
}
</ script >
</ body >
</ html >
|
Output:
Method 3: Using template literal
In this approach, we are using the template literal for printing the new line in the alert box. we are using backticks (`) to write text in between them.
Example: This example shows the implementation of the above-explained approach.
<!DOCTYPE html> < html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport" content = "width=device-width, initial-scale=1.0" >
< title >Document</ title >
</ head >
< body >
< h1 style = "color:green;" >
GeeksforGeeks
</ h1 >
< p >
Click on the button to pop
alert box with added new line.
</ p >
< button onclick = "gfg_Run()" >
click here
</ button >
< script >
let text =
`This is line 1
This is line 2`; function gfg_Run() {
alert(text);
}
</ script >
</ body >
</ html >
|
Output: