How do I add slashes to a string in Javascript?
Solution 1
replace
works for the first quote, so you need a tiny regular expression:
str = str.replace(/'/g, "\\'");
Solution 2
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, '\\"');
}
Solution 3
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.
Solution 4
To be sure, you need to not only replace the single quotes, but as well the already escaped ones:
"first ' and \' second".replace(/'|\\'/g, "\\'")
Solution 5
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.
TIMEX
Updated on July 09, 2022Comments
-
TIMEX almost 2 years
Just a string. Add \' to it every time there is a single quote.
-
Matthew Crumley over 14 yearsThose strings are identical. Unless you meant '\\x27'.
-
Kobi over 12 years@AlexeyLebedev - The second argument isn't a regex pattern - you only need one backslash in the string.
-
Alexey Lebedev over 12 yearslet's see: str = "\\'"; str = str.replace(/'/g, "\\'");
-
Alexey Lebedev over 12 yearsYields 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.
-
Kobi over 12 years@Alexey - Haaa... That's what you meant. You're right then. It's easy to fix, if it's needed.
-
Kobi over 12 yearsDear anonymous downvoter - I can only assume I didn't fulfill requirements that only exists in your head.
-
ram almost 10 yearsthis replace results with two backslash added with single quote. :(
-
Kobi almost 10 years@ram - Try to
alert
the string, or print it usingconsole.log
. It should only have one backslash, but will be displayed escaped in some tools (the debugger, for example) -
thelem over 8 yearsSupported by all browsers with greater than 0.1% global usage share, although version 8 of IE must be in standards mode.
-
buycanna.io almost 7 yearsThis function will do the opposite, hope this okay to post here...yikes.. String.prototype.stripSlashes = function(){ return this.replace(/\(.)/mg, "$1"); }