处理 vars 中带有换行符的字符串
我正试图再次得到它。
我有一个 JS var,如下所示:
var test;
现在我用 PHP 编写了一些 JS:
<?php
$phpvar = "a text with
a linebreak";
echo "<script type='text/javascript'>
var test;
test = '" . $phpvar . "';
</script>";
?>
现在,如果我运行它,它会输出如下源:
<script type='text/javascript'>
var test;
test = 'a text with
a linebreak';
</script>
这给了我一个 JS 异常:
ERROR: unterminated string literal
不知何故,JS 似乎无法识别有一个多行上的字符串。
如果最后字符串必须再次换行,我该如何实现这一点? (所以,如果所有执行完成,我必须拥有包含所有换行符的字符串)
谢谢您的帮助;)
I'm trying to get it once again.
I got a JS var which looks like this:
var test;
Now I write some JS with PHP:
<?php
$phpvar = "a text with
a linebreak";
echo "<script type='text/javascript'>
var test;
test = '" . $phpvar . "';
</script>";
?>
Now, if I run it, it outputs the source as follows:
<script type='text/javascript'>
var test;
test = 'a text with
a linebreak';
</script>
This gives me a JS exception:
ERROR: unterminated string literal
Somehow, JS seems not to recognize that there is a string on more than one line.
How can I realize this if, in the end, the string must have its linebreak again? (So, if all execution finishes, I must have the string including all linebreaks)
Thank you for your help ;)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试一下,如果在 Javascript 行末尾使用 \,则可以在字符串中使用多行。
Try this, if you use a \ at the end of a Javascript line, you can use multiple lines within a string.
在php中转义:
如果你想要这样:
在这种情况下你需要使用
\
和
(在js中),所以你需要替换\n
到\\
加\n
(在 php 中)这将换行符保留为 php,但不在 javascript 中
但如果你想保留javascript 中的换行符如下所示:
您需要添加
\n
作为转义字符串,而不是换行符。所以代码将如下所示
在这种情况下,您需要一个
\n
和一个\
和一个
(在 js 中),因此您需要将\n
替换为\\n
加\\
加\n
这会保留 php 中的换行符,并将换行符添加到JavaScript
escaping in php:
If you want this:
in this case you need to use a
\
and<linebreak>
(in js), so you need to replace the\n
to\\
plus\n
(in php)this keep the linebreaks as a php but not in the javasccript
But if you want to keep the linebreaks in javascript like this:
You need to add a
\n
as an escaped string, not as a linebreak character.So the code will look like this
In this case you need a
\n
and a\
and a<linebeak>
(in js), so you need to replace the the\n
to a\\n
plus\\
plus\n
this keeps the linebreaks in php, and also add linebreaks into the javascript