Home > Software design >  How to handle Apostrophe in Strings in Java?
How to handle Apostrophe in Strings in Java?

Time:05-06

I have the following piece of code :

public String createDownloadLink(String user) {
    String url = "No file exists";
    String fileName = "download.zip";

    if (userExists())
        url = "<a onClick= 'downloadfile(\""   user   "\", \""   Encode.forJavaScript(fileName)   "\")' href='#' >Download</a>";

    return url;
}

In the above piece of code, the user value is their respective email address. This code works fine for all email addresses except for email addresses having an apostrophe in it.

Example : For user = "john.d'[email protected]" , the url I get in response is

<a onclick="downloadfile("john.d" [email protected]", "download.zip")' href="#">Download</a>

And this is a broken url so the download fails.

I tried using

user = user.replace("'","\'");

But it still gives me the same error.

How do I fix this?

CodePudding user response:

If I understand correctly, you just need to escape the ' with a \, right? If so, your method for escaping the ' sign should look like this instead.

user = user.replace("'","\\'");

Java uses \ for escaping characters, so in your method you were saying ' should be replaced with an escaped ' which basically translates back to the '. Please correct me if I understood the question incorrectly.

CodePudding user response:

For escaping characters you could use:

StringEscapeUtils.escapeJava("john.d'[email protected]");

which results in john.d\'[email protected].

Add below dependency to your project: https://mvnrepository.com/artifact/org.apache.commons/commons-text

and this import statement:

import org.apache.commons.text.StringEscapeUtils;

Something like this should work in your case:

public String createDownloadLink(String user) {
    if (userExists()) {
       return String.format("<a onClick=\"downloadFile('%s', 'download.zip')\" href=\"#\" >Download</a>", StringEscapeUtils.escapeJava(user));
    } 

    return "No file exists";
}
  • Related