New line in JavaScript alert box

New line in JavaScript alert box

How do you put in a new line into a JavaScript alert box?

Solutions/Answers:

Solution 1:

\n will put a new line in – \n being a control code for new line.

alert("Line 1\nLine 2");

Solution 2:

 alert("some text\nmore text in a new line");

Output:

some text
more text in a new line

Solution 3:

you have to use double quotes to display special char like \n \t etc… in js alert box
for exemple in php script:

$string = 'Hello everybody \n this is an alert box';
echo "<script>alert(\"$string\")</script>";

But a second possible problem arrives when you want to display a string specified in double quoted.

see link text

If the string is enclosed in double-quotes (“), PHP will interpret more escape sequences for special characters

escape sequences \n is transformed as 0x0A ASCII Escaped character and this character is not displayed in the alert box. The solution consists in to escape this special sequence:

$s = "Hello everybody \\n this is an alert box";
echo "<script>alert(\"$string\")</script>";

if you don’t know how the string is enclosed you have to transform special characters to their escape sequences

$patterns = array("/\\\\/", '/\n/', '/\r/', '/\t/', '/\v/', '/\f/');
$replacements = array('\\\\\\', '\n', '\r', '\t', '\v', '\f');
$string = preg_replace($patterns, $replacements, $string);
echo "<script>alert(\"$string\")</script>";

Solution 4:

In C# I did:

alert('Text\\n\\nSome more text');

It display as:

Text

Some more text

Solution 5:

List of Special Character codes in JavaScript:

Code    Outputs
\'  single quote
\"  double quote
\\  backslash
\n  new line
\r  carriage return
\t  tab
\b  backspace
\f  form feed

Solution 6:

alert("text\nnew Line Text");

Modified: You don’t need to have the extra quotes and strings