Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
173
rated 0 times [  179] [ 6]  / answers: 1 / hits: 60050  / 11 Years ago, fri, march 22, 2013, 12:00:00

JSP:



<% final String data = some test with ' single quotes; %>
<script>
var str = '<%= data %>';
<script>


The result is (JavaScript):



var str = 'some test with ' single quotes';



Uncaught SyntaxError: Unexpected identifier




How do I replace this single quote with ' to avoid a JavaScript error?


More From » java

 Answers
20

Use escapeEcmaScript method from Apache Commons Lang package:




Escapes any values it finds into their EcmaScript String form. Deals
correctly with quotes and control-chars (tab, backslash, cr, ff, etc.).
So a tab becomes the characters '\' and 't'.



The only difference between Java strings and EcmaScript strings is
that in EcmaScript, a single quote and forward-slash (/) are escaped.




Example:




input string: He didn't say, Stop!



output string: He didn't say, Stop!



[#79420] Thursday, March 21, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hanna

Total Points: 66
Total Questions: 99
Total Answers: 101

Location: Saudi Arabia
Member since Sat, Aug 20, 2022
2 Years ago
;