tags:

views:

638

answers:

4

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

+12  A: 

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

Michael Gattuso
Any ideas on how cross-browser this is?
Ates Goral
as far as I know this works in every browser.
Hippo
Completely cross browser
Justin Johnson
+3  A: 
alert("some text\nmore text in a new line");

Output:

some text
more text in a new line

Amarghosh
+1  A: 

Just to inform, the \n only works with double quotes.

Jr. Hames
+1  A: 

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