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.
Post a Comment for "How Do I Add Slashes To A String In Javascript?"