yuann72
V2EX  ›  问与答

怎么在代码中对字符串进行转义?

  •  
  •   yuann72 · Mar 27, 2021 · 2035 views
    This topic created in 2057 days ago, the information mentioned may be changed or developed.
    const text = '\\n' // 转义前是一个由\和字母 n 组成的长度 2 的字符串
    console.assert(text.length === 2)
    const result = 转义(text) // 转义后变成一个换行符
    console.assert(result.length === 1)
    console.assert(result.length === '\n')
    
    function 转义() {
      // TODO 不使用字符串批量替换的方式, 如何实现? js, php, java 中各自怎么实现?
    }
    
    6 replies  •  2021-08-03 18:31:53 +08:00
    fxplay
    fxplay
    Mar 27, 2021
    1
    java>>>StringEscapeUtils ???
    ipwx
    ipwx
    Mar 27, 2021
    2
    js: JSON.stringify
    yuann72
    yuann72
    OP
    Mar 27, 2021
    3
    @ipwx #2 JSON.stringify 和 JSON.parse 都是直接报错
    QingXuJiaZhi
    QingXuJiaZhi
    Mar 27, 2021
    4
    text.replaceAll('\\n', '\n')
    hyrious
    hyrious
    Mar 28, 2021 via Android
    5
    js: eval('"' + text + '"') // 逃 / eval 换成 JSON.parse 安全点
    ruby: "\"#{text}\"".undump
    yuann72
    yuann72
    OP
    Aug 3, 2021
    6
    重新顶下这个贴,PHP 的怎么转义?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   929 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 22:17 · PVG 06:17 · LAX 14:17 · JFK 17:17
    ♥ Do have faith in what you're doing.