Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape single quotes in a string [duplicate]

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?

like image 576
Vitalii Petrychuk Avatar asked Mar 22 '13 16:03

Vitalii Petrychuk


People also ask

How do you escape a single quote from a string?

No escaping is used with single quotes. Use a double backslash as the escape character for backslash.

How do you escape a single quote within a single quote?

' End first quotation which uses single quotes. " Start second quotation, using double-quotes. ' Quoted character. " End second quotation, using double-quotes.

How do you use single quotes in a string?

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.


2 Answers

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

like image 147
VisioN Avatar answered Sep 22 '22 00:09

VisioN


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

like image 42
Juan Mendes Avatar answered Sep 20 '22 00:09

Juan Mendes