What is the difference between a single and double escape (backslash) in Javascript string?

此生再无相见时 提交于 2019-12-04 18:13:32

I think sventschui has the right idea, let me try to explain it in a different way.

When you define a string using str1='"\\101\\40\\171\\145\\154\\154\\157\\167\\40\\142\\165\\164\\164\\157\\156\\56"'

The \\ is the escape sequence and the actual string in memory is (including the quotes around it) "\101\40\171\145\154\154\157\167\40\142\165\164\164\157\156\56"


When you defined a string as str2="\101\40\171\145\154\154\157\167\40\142\165\164\164\157\156\56"

The \101,\40,... are the escape sequences and the actual string in memory is (including the quotes around it)"A yellow button"


When you create a Function(), it re-evaluates the strings (like eval), for the first case, str1 now it treats the \101, \40 as escape sequences, and the returned string is A yellow button, without the quotes around it.

When you do the same thing to the second string, there are no escape sequences, just regular characters, so the string is unchanged (except for the quotes around it)

var str1 = '"\\101"'; // "\101"
var str2 = '"\101"'; //  "A"

var str1Evaled = eval(str1); // \101 is the escape sequence, outputs A
var str2Evaled = eval(str2); // No escape sequence, a raw A

console.log({str1, str2, str1Evaled, str2Evaled});

//  Object {str1: ""\101"", str2: ""A"", str1Evaled: "A", str2Evaled: "A"}

Because you're nesting two strings both examples return the same string.


'return "\\101\\40\\171\\145\\154\\154\\157\\167\\40\\142\\165\\164\\164\\157\\156\\56"'

evaluates to

return "\101\40\171\145\154\154\157\167\40\142\165\164\164\157\156\56"

what evaluates to

A yellow button

'return "\101\40\171\145\154\154\157\167\40\142\165\164\164\157\156\56"'

evaluates to

return "A yellow button"

what evaluates to

A yellow button

Edit:

Double escaping is used because when \000 WOULD evaluate to \ the following example would mess up:

'return "\000\000"'

evaluates to

return "\\"

what evaluates to

\

'return "\\000\\000"'

evaluates to

return "\000\000"

what evaluates to

\\
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!