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.
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.
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 \\\'.
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