How to add a new line in the alert box ?
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:
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.
html
<!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:
How to add a new line in the alert box ?
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.
HTML
<!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:
alert in new line using “\r” escape character
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.
HTML
<!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:
alert in new line using template literal
Last Updated :
22 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...