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?
No escaping is used with single quotes. Use a double backslash as the escape character for backslash.
' End first quotation which uses single quotes. " Start second quotation, using double-quotes. ' Quoted character. " End second quotation, using double-quotes.
Strings in JavaScript are contained within a pair of either single quotation marks '' or double quotation marks "". Both quotes represent Strings but be sure to choose one and STICK WITH IT. If you start with a single quote, you need to end with a single quote.
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!\"
Remember you also need to encode the double quotes, new lines, tabs and many other things. One way to do it is using org.apache.commons.lang.StringEscapeUtils
public class JavaScriptEscapeTest {
public static void main(String[] args) throws Exception {
String str = FileUtils.readFileToString(new File("input.txt"));
String results = StringEscapeUtils.escapeEcmaScript(str);
System.out.println(results);
}
}
input.txt
Here is some "Text" that I'd like to be "escaped" for JavaScript. I'll try a couple special characters here: \ "
output
Here is some \"Text\" that\r\nI\'d like to be \"escaped\" for JavaScript.\r\nI\'ll try a couple special characters here: \ \"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With