3

I can't figure out how to write this so it works. We have a page where users can upload documents and the list will show on the screen. The problem comes when the filename has a single quote in it. We are using jQuery. There's some code generation going on but this is the basics of what comes out.

$(someElement).html('<label onclick="$(someOtherElement).attr(\'title\', \'TheFile\\'Name.pdf\')">Some Text</label>');

The single quote in the file name is causing a problem. I've tried escaping it both with one backslash and 2 backslashes. With a single backslash the code runs but produces this html:

<label onclick="$(someOtherElement).attr('title', 'TheFile'Name.pdf')">Some Text</label>

which now fails on the onclick.

With 2 backslashes, the jquery html() line won't run at all. In both cases I get Unexpected identifier, just at different points.

kombat
  • 343
  • 5
  • 16
  • You may want to correct what appears to be a typo in your code `#(someElement)`. I reformatted your question but didn't change the content. – j08691 Mar 19 '14 at 13:28
  • 1
    Use better jQuery functionality. For example, create a label like `$(" – Ian Mar 19 '14 at 13:28

3 Answers3

2

You need a tripple backslash :

$(someElement).html('<label onclick="$(someOtherElement).attr(\'title\', \'TheFile\\\'Name.pdf\')">Some Text</label>');

Why 3?

The first one escape the second backslash that will escape the ' in the HTML code.

The third one escape the ' to prevent the string from closing.

Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
1

You need to not just double but triple the backslashes.

The reason is that you initially escape the ' by doing \'. Now however you have two characters to escape so \ goes to \\ and ' goes to \' again giving \\\'.

Chris
  • 27,210
  • 6
  • 71
  • 92
0

How to escape single quote

Try using the character values with the & symbol to escape quotes.

Community
  • 1
  • 1
mcon
  • 679
  • 6
  • 22
  • Thanks. I tried using the character value but it behaved just as if I had tried escaping it with a single back slash. I still got the same html and the onclick fails. – kombat Mar 19 '14 at 13:39