Just a string. Add \' to it every time there is a single quote.
-
4This 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– rook2010-02-03 21:43:47 +00:00Commented 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.tim– tim2013-02-07 01:00:10 +00:00Commented Feb 7, 2013 at 1:00
-
1What 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.Sophie Swett– Sophie Swett2013-06-20 21:16:47 +00:00Commented Jun 20, 2013 at 21:16
8 Answers
replace works for the first quote, so you need a tiny regular expression:
str = str.replace(/'/g, "\\'");
7 Comments
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)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
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
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
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, '<')
.replace(/>/g, '>').replace(/\u0000/g, '\\0');
}
}
Usage: alert(str.addSlashes());