【发布时间】:2021-08-29 14:39:09
【问题描述】:
我有一个数组,我想将其转换为字符串,同时保留元素周围的引号。
例如:
["hello", "there"]
...需要看起来像这样的字符串:
'"hello", "there"'
我能做到:
["hello", "there"].toString()
但这给出了:
"hello,there"
...在元素周围没有引号。
我能做到:
["hello", "there"].join('", "')
...但这给出了:
"hello\", \"there"
...字符串中有反斜杠。
还尝试替换那些反斜杠:
["hello", "there"].join('", "').replace(/\\/, "");
...但反斜杠仍然存在:
"hello\", \"there"
最后,我们可以尝试 JSON.stringify:
JSON.stringify(["hello", "there"])
...只是为了得到:
"[\"hello\",\"there\"]"
唉,这种被误导的努力没有解决办法吗?
【问题讨论】:
-
奇怪没有人问...你为什么需要那个?你在建什么?
-
您的
JSON.stringify()方法有效。如果你console.log()它,你会看到正确的字符串! -
出于好奇,这有关系吗?
标签: javascript arrays string replace