4

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

pimvdb
  • 151,816
  • 78
  • 307
  • 352
GAgnew
  • 3,847
  • 3
  • 26
  • 28

4 Answers4

7
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.

Delan Azabani
  • 79,602
  • 28
  • 170
  • 210
2

Or this one from phpjs.org

function addslashes(str){
    return  (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}
Emmanuel
  • 4,933
  • 5
  • 46
  • 71
1

Shorter and surprisingly more efficient:

 function as(str) {
    var a = {};
    a[str] = 1;
    return JSON.stringify(a).slice(1,-3);
  }

(slice(2, -4) if you don't need quotes around string)

Andrey Sidorov
  • 24,905
  • 4
  • 62
  • 75
0

You need to escape the special character with a backslash \ . Simple and short -

let escapeString = unescapeString.replace(/([<>*()?])/g, "\\$1")

It will escape the special characters including these too.

NULL (0x00) --> \0 [This is a zero, not the letter O]

BS (0x08) --> \b

TAB (0x09) --> \t

LF (0x0a) --> \n

CR (0x0d) --> \r

SUB (0x1a) --> \Z

" (0x22) --> \"

% (0x25) --> \%

' (0x27) --> \'

\ (0x5c) --> \

_ (0x5f) --> _

Ashutosh
  • 1,029
  • 10
  • 23