tags:

views:

27

answers:

2

Hi,

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.

+1  A: 

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).

T.J. Crowder
+2  A: 

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

BalusC
Big +1, don't reinvent the wheel.
T.J. Crowder