Lumpy
Lumpy

Reputation: 3652

Safely pass string to javascript

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.

Upvotes: 2

Views: 1407

Answers (3)

user2138983
user2138983

Reputation: 1333

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

"

Upvotes: 0

Justin Thomas
Justin Thomas

Reputation: 5848

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

Upvotes: 1

orangegoat
orangegoat

Reputation: 2703

Replacing the double quotes with &quot; should work

Upvotes: 0

Related Questions