开发者

set a text from a java object with new lines to a javascript variable in JSP

开发者 https://www.devze.com 2022-12-23 10:19 出处:网络
I\'ve a Java String with new lines(\\n), say for example String value = \"This is a variable\\n\\nfrom\\nJava\";

I've a Java String with new lines(\n), say for example

String value = "This is a variable\n\nfrom\nJava";

Now I've to set this to a Javascript variable in a JSP file,

<script>var val 开发者_运维知识库= '<%= value %>';</script>

But because of the new lines in the above line, I'm getting javascript error "Unterminated String".

Please help me.


Use StringEscapeUtils#escapeEcmaScript() before printing it to JSP.


Newlines will be only one issue. To properly escape the string for display as a JavaScript literal, you have to handle newlines and a wide variety of other characters (not least backslashes and whatever quotes you're using). This isn't hard, but it's non-trivial. Effectively you need to search the string for a range of values (regular expressions are useful here) and substitute the JavaScript escape code (\n, etc.) for it. To avoid charset issues, when doing this sort of thing I escape anything that isn't ASCII into either the JavaScript named escape (\n) or a Unicode escape (\u1234).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号