javascript 如何将换行符转换为 \n
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10209413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert line breaks to \n
提问by dev.bashar
I have a return string from a db.
我有一个来自数据库的返回字符串。
The return string must be formatted in javascript.
返回字符串必须在 javascript 中格式化。
<?php
$db = "this is a line
this is a new line";
?>
How would I convert the above to:
我将如何将上述内容转换为:
<?php $db = "this is a line \n this is a new line"; ?>
Javascript:
Javascript:
<script>
var jdb = <?php echo $db; ?>
</script>
回答by DaveRandom
Try this (updated 2014-11-08):
试试这个(更新 2014-11-08):
<?php
$db = "this is a line
this is a new line
";
?>
<script type="text/javascript">
var jdb = <?php echo json_encode($db) ?>;
</script>
回答by Fabrizio Calderan
$db = preg_replace("/\n/m", '\n', $db);
should do the trick
应该做的伎俩
回答by redolent
回答by AL-Kateb
i don't get the point, but you can (escape the line break by adding a backslash)
我不明白这一点,但你可以(通过添加反斜杠来逃避换行符)
$db = str_replace("\n","\n",$db);
回答by Satish N Ramteare
$db = str_replace("\r\n", "\n", $db);
回答by craniumonempty
You want to output that to javascript... hmm, so if you want to insert it into html you probably want something like this (the test ran):
你想把它输出到 javascript... 嗯,所以如果你想把它插入到 html 中,你可能想要这样的东西(测试运行):
<div id="test"></div>
<script type="text/javascript">
<?php
$string = "123
456"; // or $string = "123\n456";
$string = str_replace(array("\r\n","\n"),"\\n",$string);
echo "document.getElementById('test').innerHTML = '".htmlentities($string)."';";
?>
</script>
with output 123\n 456
to the div through the js
123\n 456
通过js输出到div
If you simply want it as that in js, just remove two of the slashes so it's "\n" in php and "\n" in js.
如果你只是想要它在 js 中,只需删除两个斜杠,所以它在 php 中是“\n”,在 js 中是“\n”。
回答by Philipp
I am not sure if I understand correctly because \n is a line break!?
我不确定我是否理解正确,因为 \n 是换行符!?
But you may be need:
但您可能需要:
$db = str_replace("\r\n", "\n", $db);
回答by Jared
You should look at nl2br(), which converts all new lines to HTML <br />. http://php.net/manual/en/function.nl2br.php
您应该查看 nl2br(),它将所有新行转换为 HTML <br />。 http://php.net/manual/en/function.nl2br.php