New line in JavaScript alert box

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

alert("Line 1\nLine 2");


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

Output:

some text
more text in a new line


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>";

Tags:

Javascript