Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"\\

like image 917
GAgnew Avatar asked Dec 27 '22 15:12

GAgnew


1 Answers

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.

like image 75
Delan Azabani Avatar answered Jan 08 '23 06:01

Delan Azabani