Search code examples
javascriptregexescapingaddslashes

addslashes JavaScript equivalent


I am looking for a proper version of a JavaScript equivalent of PHP's addSlashes.

I have found many versions, but none of them handle \b, \t, \n, \f or \r.

http://jsfiddle.net/3tEcJ/1/

To be complete, this jsFiddle should alert: \b\t\n\f\r"\\


Solution

  • 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, '\\"');
    }
    

    Notice how I've used \u0008 to replace \b with \\b. JavaScript's regex syntax doesn't appear to accept \b, but it does accept \u0008. JavaScript's string literal syntax recognises both \b and \u0008.