【问题标题】:javascript error with carriage return and newline带有回车符和换行符的 javascript 错误
【发布时间】:2013-07-11 20:12:22
【问题描述】:

我在 Java 中有以下字符串:

"this is text1\r\nthis is text2\r\nthis is text3"

我将\r\n 替换为<br/>,如下所示:

String temp = "this is  text1\r\nthis is text2\r\nthis is text3"
temp = temp.replaceAll("[\r\n]+", "<br/>");

产生以下字符串:"is text1 this is text2 this is text3"

现在,我想将它发送到 JavaScript 元素,如下所示:

var desc_str = "<%=temp%>";
document.getElementById('proc_desc').value = desc_str;

Java 的输出很好,但是在传递给 HTML 元素后,我收到 JavaScript 错误“未终止的字符串文字”,我没有找到线索,请帮忙。

【问题讨论】:

  • 不熟悉Java,但你试过用JSON编码吗?
  • @Ian 将解决 scriplets 使用的问题,但认为它不会对 JavaScript 客户端有所帮助。
  • 为什么不在您的问题中包含生成的 JavaScript 代码?你有没有看过它?我认为通过查看生成的 JavaScript,答案会非常明显。
  • 值打印出来的时候有没有杂散的引号?

标签: java javascript replaceall


【解决方案1】:

听起来你还没有从你的字符串中得到所有的换行符。

您可能会发现这篇文章很有帮助: How do I replace all line breaks in a string with <br /> tags?

【讨论】:

  • 我找到了解决方案,问题是在将 java 字符串传递给 javascript 变量时 \r\n 的转义/取消转义。无需将 \r\n 替换为
    ,只需将 java 字符串 tmpProPrDesc = StringEscapeUtils.escapeJavaScript(tmpProPrDesc); 转义即可。 var desc_str = ""; document.getElementById('proc_desc').value = desc_str;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-17
  • 2015-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-09
  • 2017-06-28
相关资源
最近更新 更多