6

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vitalii Petrychuk
  • 14,035
  • 8
  • 51
  • 55

3 Answers3

6

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!\"

VisioN
  • 143,310
  • 32
  • 282
  • 281
  • 4
    Definitely an overkill, because it also converts any non-latin alphabetic symbol into its unicode sequence (`"кириллица"` -> `"\\u043A\\u0438\\u0440\\u0438\\u043B\\u043B\\u0438\\u0446\\u0430"`). – Mikhail Batcer Oct 23 '15 at 08:07
3

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: \ \"

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
-1

Are you looking to simply double-escape your string so you actually have a \ followed by a '?

<% final String data = "some name with \\' single quote"; %>

From your JavaScript code, you can use the string replace functionality:

var str2 = str1.replace("'","\\'"); 
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131