开发者

addslashes JavaScript equivalent

开发者 https://www.devze.com 2023-03-29 21:56 出处:网络
I am looking for a proper version of a JavaScript equivalent of PHP\'s 开发者_如何学JAVAaddSlashes.

I am looking for a proper version of a JavaScript equivalent of PHP's 开发者_如何学JAVAaddSlashes.

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


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.


Or this one from phpjs.org

function addslashes(str){
    return  (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}


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)


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) --> _

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号