gpt4 book ai didi

javascript - 替换 "with\"

转载 作者:行者123 更新时间:2023-11-30 08:03:46 26 4
gpt4 key购买 nike

我正在尝试用 \" 替换所有 " 并用 JSON 解析字符串,但浏览器抛出错误 SyntaxError: JSON Parse error: Unrecognized token '\'.

下面是代码。字符串 a 的 JSON.parsed 很好,但是尽管我将字符串 b 中的所有 " 替换为 \",因此它应该与字符串 a 相同,但解析失败。我在 JSBIN 中有代码.

var a = '[\"{\\"objects\\":[],\\"background\\":\\"#fff\\"}\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"]';

var b = '["{\"objects\":[],\"background\":\"#fff\"}","","","","","","","","",""]';

// Replace " with \"
// Charcode 92 is \
b = b.replace('"', String.fromCharCode(92)+'"', "g");

a = JSON.parse(a);
console.log(a);
b = JSON.parse(b);
console.log(b);

知道吗,我如何使用 JSON.parse 解析字符串 b?如果我手动将所有 " 替换为 \",它会很好地解析,但我正在寻求自动化的方式。

最佳答案

重点是使用 2 \:

b = b.replace(/"/g,'\\"')

结果是:

[\"{\"objects\":[],\"background\":\"#fff\"}\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"]

正如@isherwood 所说:

To be more clear, the backslash is an escape character, so you need to double it so there's an actual character behind the escape.

关于javascript - 替换 "with\",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21662695/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com