47

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

3
  • 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. Commented Feb 3, 2010 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. Commented Feb 7, 2013 at 1: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. Commented Jun 20, 2013 at 21:16

8 Answers 8

80

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

str = str.replace(/'/g, "\\'");
Sign up to request clarification or add additional context in comments.

7 Comments

@AlexeyLebedev - The second argument isn't a regex pattern - you only need one backslash in the string.
let's see: str = "\\'"; str = str.replace(/'/g, "\\'");
Dear anonymous downvoter - I can only assume I didn't fulfill requirements that only exists in your head.
this replace results with two backslash added with single quote. :(
@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)
|
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, '\\"');
}

1 Comment

This function will do the opposite, hope this okay to post here...yikes.. String.prototype.stripSlashes = function(){ return this.replace(/\(.)/mg, "$1"); }
25

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.

1 Comment

Supported by all browsers with greater than 0.1% global usage share, although version 8 of IE must be in standards mode.
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, "\\'")

Comments

4
var myNewString = myOldString.replace(/'/g, "\\'");

Comments

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.

1 Comment

Those strings are identical. Unless you meant '\\x27'.
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: \'

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.