2

I am trying to pass a string from my java code to javascript like so:

myData.data = "${data.myString}";

This breaks if myString contains a "

I tried storing a javascript safe string instead, just replacing " with \" but then when I use myString in my jsp I get an ugly output with \" showing instead of "

What is the best way to safely pass a string and not mess up the rest of my output.

merlin2011
  • 71,677
  • 44
  • 195
  • 329
Lumpy
  • 3,632
  • 4
  • 34
  • 58

3 Answers3

1

Encode it into the html in the JSP:

<input id="test_hide" type="hidden" value="${URIUtil.encodeAll("http://www.google.com?q=a b","UTF-8")}">

Then in the JavaScript:

 myData.data = decodeURIComponent(document.getElementById('test_hide').getAttribute('value'));

Java - Convert String to valid URI object

Community
  • 1
  • 1
Justin Thomas
  • 5,680
  • 3
  • 38
  • 63
0

Replacing the double quotes with &quot; should work

Zach Lysobey
  • 14,959
  • 20
  • 95
  • 149
orangegoat
  • 2,523
  • 1
  • 15
  • 17
0

A bad solution :

Check if your string has double quotes, if yes then use

myData.data = '${data.myString}';

if it contains single quotes use

myData.data = "${data.myString}";

This will explode if you have both single and double quotes.

A good solution :

Just use

&quot;
user2138983
  • 1,313
  • 9
  • 15