V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
yuann72
V2EX  ›  问与答

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

  •  
  •   yuann72 · Mar 27, 2021 · 1576 views
    This topic created in 1866 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
        1
    fxplay  
       Mar 27, 2021
    java>>>StringEscapeUtils ???
    ipwx
        2
    ipwx  
       Mar 27, 2021
    js: JSON.stringify
    yuann72
        3
    yuann72  
    OP
       Mar 27, 2021
    @ipwx #2 JSON.stringify 和 JSON.parse 都是直接报错
    cmdOptionKana
        4
    cmdOptionKana  
       Mar 27, 2021
    text.replaceAll('\\n', '\n')
    hyrious
        5
    hyrious  
       Mar 28, 2021 via Android
    js: eval('"' + text + '"') // 逃 / eval 换成 JSON.parse 安全点
    ruby: "\"#{text}\"".undump
    yuann72
        6
    yuann72  
    OP
       Aug 3, 2021
    重新顶下这个贴,PHP 的怎么转义?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1060 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 22:55 · PVG 06:55 · LAX 15:55 · JFK 18:55
    ♥ Do have faith in what you're doing.