Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.html() with single quotes

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.

like image 500
kombat Avatar asked Dec 28 '25 16:12

kombat


2 Answers

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.

like image 59
Karl-André Gagnon Avatar answered Dec 31 '25 07:12

Karl-André Gagnon


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

like image 38
Chris Avatar answered Dec 31 '25 06:12

Chris