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

2021-03-27 15:06:10 +08:00
 yuann72
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 中各自怎么实现?
}
822 次点击
所在节点    问与答
6 条回复
fxplay
2021-03-27 15:17:58 +08:00
java>>>StringEscapeUtils ???
ipwx
2021-03-27 15:27:32 +08:00
js: JSON.stringify
yuann72
2021-03-27 15:35:51 +08:00
@ipwx #2 JSON.stringify 和 JSON.parse 都是直接报错
cmdOptionKana
2021-03-27 15:57:46 +08:00
text.replaceAll('\\n', '\n')
hyrious
2021-03-28 00:28:15 +08:00
js: eval('"' + text + '"') // 逃 / eval 换成 JSON.parse 安全点
ruby: "\"#{text}\"".undump
yuann72
2021-08-03 18:31:53 +08:00
重新顶下这个贴,PHP 的怎么转义?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/765681

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX