45

I need to escape single quotes in JavaScript function parameters to avoid this:

onclick="Javascript:INSERT_PRODUCT('188267','WILL AND GRACE','32311','L'ANNIVERSARIO DINOZZE ','20101113|04|18|','13/11/2010 0.00.00','CANALE 5  ',this);"

But I need to escape them inside a function call since I do not know the values that will be passed (db variables I can't escape from the database).

Is there a function that allows me to do something like the following?

onclick="Javascript:function(escape(param1), escape(param2), escape(param3));"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Daniele Di Punzio
  • 503
  • 2
  • 5
  • 7
  • 3
    `'` = `\'` (Just as you would a normal string). And because you're inserting it in the markup, either _you_ would need to escape it, or if a server-side language is generating it make sure _it_ escapes it. – Brad Christie Jan 05 '12 at 14:42
  • Yyou can put your parameters inside `escape(param)` – Emmanuel N Jan 05 '12 at 14:44
  • 4
    The label `Javascript:` is not needed there. You should use other ways to bind event handlers: http://www.quirksmode.org/js/introevents.html, then you don't have to worry about quotes. – Felix Kling Jan 05 '12 at 14:44
  • @EmmanuelN: `escape` url escapes it, not translates quotes. – Brad Christie Jan 05 '12 at 14:45
  • @DanieleDiPunzio: For a definitive answer, can you show how you're generating the markup? Is this PHP, ASP, etc. generated, or are you hard-coding the onclick binding yourself? (If you're hard-coding it, you'll just need to be conscience of replacing the quotes--nothing is going to do it for you.) – Brad Christie Jan 05 '12 at 14:46
  • I tried using escape(param) but the result is myfunction('', '', '') ando so on... – Daniele Di Punzio Jan 05 '12 at 14:46
  • Unfortunately I'm using an internal software developed by my company. this product generates vb.net and html code with hardcoded stuff. I can only define an onclick function for my button, that's why I should escape single quotes in function call. – Daniele Di Punzio Jan 05 '12 at 14:50
  • 2
    Look into HTML Attribute escaping: http://stackoverflow.com/questions/4015345/how-to-properly-escape-quotes-inside-html-attributes – TJR Jan 05 '12 at 14:52

7 Answers7

20
 JSON.stringify(plainTextStr).replace(/&/, "&").replace(/"/g, """)

will produce a string you can safely embed in a quoted attribute and which will have the same meaning when seen by the JavaScript interpreter.

The only caveat is that some Unicode newlines (U+2028 and U+2029) need to be escaped before being embedded in JavaScript string literals, but JSON only requires that \r and \n be escaped.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
11

Escape the apostrophe with a backslash:

onclick="INSERT_PRODUCT('188267','WILL AND GRACE ','32311','L\'ANNIVERSARIO DI NOZZE ','20101113|04|18|','13/11/2010 0.00.00','CANALE 5 ',this);"
Iain M Norman
  • 2,075
  • 15
  • 30
  • 4
    Please remove the `Javascript:`. It's not wrong to put it there, but it is of no use either and less experienced developers might think it is needed. – Felix Kling Jan 05 '12 at 14:52
  • 2
    I need a function to perform the escape inside the myfunction call since that's the only place I can access. Any suggestion? – Daniele Di Punzio Jan 05 '12 at 14:57
  • This will fail if the string contains `"`, ``, '\' or any other entity that encodes single or double quotes or backslash. For example, the string `'foo " onmouseover=alert(1)` contains no single quote, yet when embedded in an HTML attribute, exploits an XSS vulnerability. Similarly, `'foo \` will fail, because the JavaScript parser will see `\`, not `\` so the close quote will be interpreted as part of the string so if the next string value is ` alert(1)) // `, then that will be treated as literal JavaScript, resulting in arbitrary script execution too. – Mike Samuel Dec 23 '14 at 16:26
7

It's maybe not totally clear from the question, but assuming that all you want is to send this to a PHP script for storing in a database, you of course would ideally utilize PHP's various methods such as stripslashes() -- but if you're really not trying to get too fancy, simply adding 1 slash in front of any single quote is enough to send a SQL query right into PHP from the client-side. It's not safe, but maybe not necessary either.

str.replace(/'/g, "\\'"); // escaping \ with \, so used 2x

does the trick., like for example in something like this:

var body = $('#body').val().replace(/'/g, "\\'");
myCustomSQLqueryFunction("UPDATE mytable SET `content`='"+ body +"';" );

MySQL will now store your body like you see it in the form field.

tim
  • 3,823
  • 5
  • 34
  • 39
  • I was testing this and noticed that MySQL simply removes fancy single quotes like ` so you'd have to escape those as well. – tim Feb 07 '13 at 01:29
3

This function worked for me (it removes and restores the quote again): Guessing that the data to be sent is the value of an input element,

var Url = encodeURIComponent($('#userInput').val().replace("'","\\'"));

Then get the original text again:

var originalText = decodeURIComponent(Url);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Irrmich
  • 436
  • 4
  • 15
1
var cmpdetail = cmpdetail.replace(/'/g, "\\'");

its working for me.

amit
  • 429
  • 5
  • 8
  • 20
0

I prefer to use single quote for defining JavaScript strings. Then I escape my embedded double quotes as follows.

This is how I do it, basically str.replace(/[\""]/g, '\\"').

var display = document.getElementById('output');
var str = 'class="whatever-foo__input" id="node-key"';
display.innerHTML = str.replace(/[\""]/g, '\\"');

//will return class=\"whatever-foo__input\" id=\"node-key\"
<span id="output"></span>
Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91
0

I encountered a similar issue recently, and solved it by replacing the single quote with the corresponding unicode (&#39;)

Initially my code was this, resulting in me getting results that were cut off (e.g. Jane's Coffee became just Jane in the output).

b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";

When I introduced unicode replacement (shown below), I got the exact output I wanted

b.innerHTML += "<input type='hidden' value='" + arr[i].replace("'", "&#39;") + "'>";
Kenneth Leung
  • 300
  • 3
  • 8