JSON.parsereplace提供的结果与str.replace不同

问题描述

以下代码片段让我有些困惑。我希望结果是一样的:

// # Base for all,used in method 1 directly
const content = `Amazon,? bezahlte EUR 75.60 am Amazon
? Heute ausgegeben: EUR 75.60`

// # Base for method 2
const newString = JSON.stringify(content)
const replaceString = newString.replace('\n',',')

// # Base for method 3
const newReplaceString = content.replace('\n',')

// # Output from method 1
console.log(JSON.parse(JSON.stringify(content).replace('\n',')));
> "Amazon,? bezahlte EUR 75.60 am Amazon
? Heute ausgegeben: EUR 75.60"

// # Output from method 2
console.log(replaceString)
> ""Amazon,? bezahlte EUR 75.60 am Amazon\n? Heute ausgegeben: EUR 75.60""

// # Output from method 3
console.log(newReplaceString)
> "Amazon,? bezahlte EUR 75.60 am Amazon,? Heute ausgegeben: EUR 75.60"

为什么字符串化对象上的replace函数不相同?我需要做些什么?

解决方法

换行符\n(一个字符)变成两个字符\n,您应该这样替换它:

const replaceString = newString.replace('\\n',',');

如果您可以在控制台的字符串中看到实际的字符源(即反斜杠\本身,其后是任何字符),则意味着该字符实际上分为两个字符。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...