如何处理JavaScript中的换行符? (来自PHP) [英] How to handle newlines in Javascript? (from PHP)

查看:152
本文介绍了如何处理JavaScript中的换行符? (来自PHP)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

 <?php 
echo'< script type =text / JavaScript的>';
echo'var out ='。$ txt。';';
echo'< / script>';
?>

其中$ txt是一个PHP变量,可以包含像这样的换行符:

  line1 
line2 hello world

其中最终会如此:

  var out =line1 
line2 hello world;

当然会导致Javascript错误。



处理这个问题的最佳方法是什么? out变量将用于HTML textarea,所以我不认为它可以被解析为< br>

解决方案

  $ txt = str_replace(array(\\\
,\r),array(\\ n,\\r),$ txt);

应该替换换行符。 不要这样做

这是字符串转义对于JavaScript 。因为你实际上试图格式化一个字符串以便在JavaScript中使用,所以更好的解决方案是使用 json_encode

  $ txt = json_encode($ txt); 
echo< script> var out = {$ txt};< / script>;

json_encode 将正确地转义字符串中的特殊字符,如引号,选项卡,表单提要和其他特殊的Unicode字符。它还将执行转换对象,数组,数字和布尔值的所有正确转义。


I have code like this:

<?php
echo '<script type="text/javascript">';
echo 'var out="'.$txt.'";';
echo '</script>';
?>

Where $txt is a PHP variable that can contain newlines like this:

line1
 line2 hello world

Which would end up like this:

var out="line1
 line2 hello world";

Which will cause a Javascript error, of course.

What is the best way to handle this? The out variable will be used in a HTML textarea, so I don't think it can be parsed into <br>

解决方案

$txt = str_replace( array( "\n", "\r" ), array( "\\n", "\\r" ), $txt );

should replace newlines. Don't do it this way.

This is a naïve implementation of string escaping for JavaScript. As you're actually trying to format a string for use in JavaScript, a much better solution would be to use json_encode:

$txt = json_encode($txt);
echo "<script>var out={$txt};</script>";

json_encode will correctly escape special characters in strings, such as quotes, tabs, form feeds, and other special unicode characters. It will also perform all the correct escaping for converting objects, arrays, numbers, and booleans.

这篇关于如何处理JavaScript中的换行符? (来自PHP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆