Question
How do I add slashes to a string in Javascript?
Just a string. Add \' to it every time there is a single quote.
45 159535
45
Question
Just a string. Add \' to it every time there is a single quote.
Solution
replace
works for the first quote, so you need a tiny regular expression:
str = str.replace(/'/g, "\\'");
Solution
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, '\\"');
}