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.

11
  • not a robust solution, but can you use single quotes instead? Commented Feb 18, 2013 at 20:58
  • One possibility would be to base64-encode it? Commented Feb 18, 2013 at 20:58
  • did you try to use ' (single quote) instead of " (double quote). you maybe also need to escape this. Commented Feb 18, 2013 at 20:58
  • single quotes causes the same problem, these are user submitted comments that can legitimately contain ' and " Commented Feb 18, 2013 at 20:58
  • 2
    have you tried replacing with "? Commented Feb 18, 2013 at 21:02

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah I had that originally. My use of URLEncoder is fuzzy :) Thanks
0

Replacing the double quotes with &quot; should work

Comments

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.