CSS.escape('12345')
返回 \31 2345
,但是没有 CSS.unescape() 函数。
我该如何使用 Javascript 将
\31 2345
转换回 12345
?
const chr = cp => cp > 0 && cp <= 0x10FFFF ? String.fromCodePoint(cp) : '\ufffd'
const replacer = (s, hex, skip, ch) => ch ?? (skip ? '' : chr(parseInt(hex, 16)))
const re_quoted = /\\([0-9a-f]{1,6}\s?|$)|\\(\r?\n|\f)|\\(.)/ig
const re_normal = /\\([0-9a-f]{1,6}\s?|$)|\\()(.)/ig
const CSSUnescape = (s, quoted = false) => s.replace(quoted ? re_quoted : re_normal, replacer)
您可以使用以上
CSSUnescape
功能。
由于反斜杠
\
后跟回车 CR
、换行 LF
或换页 FF
字符在带引号的字符串中与不带引号的字符串中时的含义有所不同,因此该函数接受第二个参数是为了知道它应该以哪种方式工作。然而 FF
或多或少不再使用,其他组合很少用于在手动编写 CSS 时将长 CSS 字符串拆分为多行。如果您真的只关心 CSS.escape
,它永远不会生成这些组合,因此您可以忽略第二个参数,甚至可以在没有它的情况下简化函数。