如何在JavaScript警告框中添加新行?


当前回答

你必须使用双引号来显示特殊字符,如\n \t等…在js中的警告框 例如在PHP脚本中:

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

但是,当您希望显示以双引号指定的字符串时,可能会出现第二个问题。

参见链接文本

如果字符串用双引号(")括起来,PHP将为特殊字符解释更多转义序列

转义序列\n被转换为0x0A ASCII转义字符,该字符不会显示在警告框中。解决方案包括转义这个特殊的序列:

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

如果您不知道字符串是如何封装的,则必须将特殊字符转换为它们的转义序列

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

其他回答

我使用了:"\n\r" -它只能在双引号中使用。

var fvalue = "foo";
var svalue = "bar";
alert("My first value is: " + fvalue + "\n\rMy second value is: " + svalue);

will alert as:

My first value is: foo
My second value is: bar

当你想用javascript写一个php变量的alert时,你必须在“\n”之前加一个“\”。 相反,弹出的警告不起作用。

ex:

PHP :
$text = "Example Text : \n"
$text2 = "Example Text : \\n"

JS:
window.alert('<?php echo $text; ?>');  // not working
window.alert('<?php echo $text2; ?>');  // is working

\n将不会工作,如果你在Java代码中:

<% System.out.print("<script>alert('Some \n text')</script>"); %>

我知道这不是答案,只是觉得这很重要。

只是为了帮助任何人,当从c#代码后面这样做时,我必须使用双转义字符,否则我会得到一个“未终止字符串常量”JavaScript错误:

ScriptManager.RegisterStartupScript(this, this.GetType(), "scriptName", "alert(\"Line 1.\\n\\nLine 2.\");", true);

警报('交易已被批准。\ nThank你);

只需添加一个换行符\n。

alert('The transaction has been approved.\nThank you');
//                                       ^^