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
1 Jan 1970

Solution

 77

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

str = str.replace(/'/g, "\\'");
2010-02-03

Solution

 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, '\\"');
}
2012-07-30