【问题标题】:using string.replace before and after JSON.stringify brings different results在 JSON.stringify 前后使用 string.replace 会带来不同的结果
【发布时间】:2021-08-19 10:34:43
【问题描述】:

以下代码示例显示了replace 方法的意外行为:

let str = "some long string\nwith line\nbreaks"
console.log(str.replace(/\n/g,''))
str = JSON.stringify(str)
console.log(str.replace(/\n/g,''))

我看到documentation 中有一些关于JSON.stringify 用法的警告,并且here 对类似问题的讨论已有七年之久。

JSON.stringify 究竟对替换不起作用的字符串做了什么?

【问题讨论】:

  • JSON.parse(str).replace(/\n/g,'') 你的字符串被序列化了,它现在是一个包含字符串的字符串。解析它以取回原来的
  • 你为什么在字符串上使用JSON.stringify?这样做有完全正当的理由,但这也是人们错误地做的事情,所以我认为这可能有助于检查。
  • 我的同事刚刚使用它并偶然发现了这种情况,我无法理解出了什么问题,是的,我也尝试使用JSON.stringify 通常在将对象写入文件之前进行序列化。跨度>

标签: javascript json string


【解决方案1】:

它将换行符更改为序列\n,因为文字换行符在 JSON 中无效。所以之后的replace 找不到任何换行符,因为它们不再存在。

你可以通过查看JSON.stringify之前和之后的字符串来看到它:

function hex2(v) {
    return "0x" + v.toString(16).padStart(2, "0").toUpperCase();
}
function showCodePoints(label, str) {
    console.log(label + ":");
    for (const ch of [...str]) {
        const lit = ch === "\n" ? "<newline>" : ch === "\\" ? "<backslash>" : ch;
        const cp = hex2(ch.codePointAt(0));
        console.log(`  ${lit.padEnd(12)} (${cp})`);
    }
}
let str = "X\nY\nZ";
showCodePoints("before", str);
str = JSON.stringify(str);
showCodePoints("after", str);
.as-console-wrapper {
    max-height: 100% !important;
}

【讨论】:

  • 打印消息无助于了解情况是否如此。有没有办法以某种方式看到这些变化?
  • @FarrukhNormuradov - 您可以在调试器中检查字符串,尽管有时这可能有点令人困惑。我添加了一个代码示例,显示以另一种方式检查字符串,也许这有帮助。基本点是"X\nY" 是一个字符串字面量,它定义了一个包含三个字符的字符串:X、换行符和Y。如果你通过JSON.stringify 传递它,你会得到一个包含六个字符的字符串:"X、反斜杠、nY"
  • * 帮助(不是“帮助”)
【解决方案2】:

let str = "some long string\nwith line\nbreaks"
console.log(str.replace(/\n/g,''))
str = JSON.stringify(str).replace(/\\n/g, '');
console.log(str)

JSON.stringify() 方法将 JavaScript 对象或值转换为 JSON 字符串。 在 stringfy 之后,字符串不包含换行符 (\n),但它是 (\\n)。它还在 stringfy 之后在字符串的开头和结尾添加 "。

要删除这些,请使用 .replace(/\\n/g, '') 而不是 .replace(/\n/g, '')

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 2016-07-01
    • 2012-06-01
    • 2022-01-20
    • 2016-09-02
    相关资源
    最近更新 更多