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
2009-12-03 17:17:04
Any ideas on how cross-browser this is?
Ates Goral
2009-12-03 18:22:23
as far as I know this works in every browser.
Hippo
2009-12-03 18:26:21
Completely cross browser
Justin Johnson
2009-12-03 20:44:20
+3
A:
alert("some text\nmore text in a new line");
Output:
some text
more text in a new line
Amarghosh
2009-12-03 17:17:45
+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
2010-08-30 14:31:32