45

Just a string. Add \' to it every time there is a single quote.

Somnath Muluk
  • 55,015
  • 38
  • 216
  • 226
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
  • 4
    This better not be for sql injection prevention, because an attacker can easily bypass this. Exploit code doesn't have to execute your javascript, it will just send the request. Escaping and sanitizing input should always be done on the server side. – rook Feb 03 '10 at 21:43
  • Or, you might just want to save yourself some PHP and do it on the client side as the question specifically asks. – tim Feb 07 '13 at 01:00
  • 1
    What Rook is saying is that you *should not* save yourself some PHP and do it on the client side, because an attacker can easily bypass any client-side code. – Tanner Swett Jun 20 '13 at 21:16

8 Answers8

76

replace works for the first quote, so you need a tiny regular expression:

str = str.replace(/'/g, "\\'");
Kobi
  • 135,331
  • 41
  • 252
  • 292
  • @AlexeyLebedev - The second argument isn't a regex pattern - you only need one backslash in the string. – Kobi Oct 25 '11 at 11:10
  • let's see: str = "\\'"; str = str.replace(/'/g, "\\'"); – Alexey Lebedev Oct 25 '11 at 13:46
  • Yields a string with an escaped slash and *unescaped* quote. While your example is a correct answer to the question, it doesn't escape string properly. – Alexey Lebedev Oct 25 '11 at 13:53
  • @Alexey - Haaa... That's what you meant. You're right then. It's easy to fix, if it's needed. – Kobi Oct 25 '11 at 15:58
  • 13
    Dear anonymous downvoter - I can only assume I didn't fulfill requirements that only exists in your head. – Kobi Nov 12 '11 at 09:36
  • this replace results with two backslash added with single quote. :( – ram Jun 20 '14 at 09:54
  • @ram - Try to `alert` the string, or print it using `console.log`. It should only have one backslash, but will be displayed escaped in some tools (the debugger, for example) – Kobi Jun 20 '14 at 10:09
42

Following JavaScript function handles ', ", \b, \t, \n, \f or \r equivalent of php function addslashes().

function addslashes(string) {
    return string.replace(/\\/g, '\\\\').
        replace(/\u0008/g, '\\b').
        replace(/\t/g, '\\t').
        replace(/\n/g, '\\n').
        replace(/\f/g, '\\f').
        replace(/\r/g, '\\r').
        replace(/'/g, '\\\'').
        replace(/"/g, '\\"');
}
Somnath Muluk
  • 55,015
  • 38
  • 216
  • 226
  • This function will do the opposite, hope this okay to post here...yikes.. String.prototype.stripSlashes = function(){ return this.replace(/\\(.)/mg, "$1"); } – buycanna.io Aug 15 '17 at 03:08
23

A string can be escaped comprehensively and compactly using JSON.stringify. It is part of JavaScript as of ECMAScript 5 and supported by major newer browser versions.

str = JSON.stringify(String(str));
str = str.substring(1, str.length-1);

Using this approach, also special chars as the null byte, unicode characters and line breaks \r and \n are escaped properly in a relatively compact statement.

filip
  • 3,542
  • 1
  • 26
  • 23
  • 3
    Supported by all browsers with greater than 0.1% global usage share, although version 8 of IE must be in standards mode. – thelem Sep 21 '15 at 10:14
6

To be sure, you need to not only replace the single quotes, but as well the already escaped ones:

"first ' and \' second".replace(/'|\\'/g, "\\'")
Mic
  • 24,812
  • 9
  • 57
  • 70
4
var myNewString = myOldString.replace(/'/g, "\\'");
womp
  • 115,835
  • 26
  • 236
  • 269
4

An answer you didn't ask for that may be helpful, if you're doing the replacement in preparation for sending the string into alert() -- or anything else where a single quote character might trip you up.

str.replace("'",'\x27')

That will replace all single quotes with the hex code for single quote.

lance
  • 16,092
  • 19
  • 77
  • 136
3
var str = "This is a single quote: ' and so is this: '";
console.log(str);

var replaced = str.replace(/'/g, "\\'");
console.log(replaced);

Gives you:

This is a single quote: ' and so is this: '
This is a single quote: \' and so is this: \'
Vincent Robert
  • 35,564
  • 14
  • 82
  • 119
Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
3
if (!String.prototype.hasOwnProperty('addSlashes')) {
    String.prototype.addSlashes = function() {
        return this.replace(/&/g, '&') /* This MUST be the 1st replacement. */
             .replace(/'/g, ''') /* The 4 other predefined entities, required. */
             .replace(/"/g, '"')
             .replace(/\\/g, '\\\\')
             .replace(/</g, '&lt;')
             .replace(/>/g, '&gt;').replace(/\u0000/g, '\\0');
        }
}

Usage: alert(str.addSlashes());

ref: https://stackoverflow.com/a/9756789/3584667

Community
  • 1
  • 1