将数组转换为字符串,同时保留元素周围的引号
Convert array to string while preserving the quotes around the elements
我有一个数组,我想将其转换为字符串,同时保留元素周围的引号。
例如:
["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\"]"
唉,这种误入歧途的努力就没有解决办法了吗?
您可以简单地使用 join()
和 template literals
。
function convert(arrData) {
return `'"${arrData.join('", "')}"'`;
}
const a = ["hello", "there"];
console.log(convert(a));
map
over the elements and create an array of strings from them, and then join
那个数组最多组成一个新的字符串。
const arr = ["hello", "there"];
const str = `'${arr.map(el => `"${el}"`).join(', ')}'`;
console.log(str);
我有一个数组,我想将其转换为字符串,同时保留元素周围的引号。
例如:
["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\"]"
唉,这种误入歧途的努力就没有解决办法了吗?
您可以简单地使用 join()
和 template literals
。
function convert(arrData) {
return `'"${arrData.join('", "')}"'`;
}
const a = ["hello", "there"];
console.log(convert(a));
map
over the elements and create an array of strings from them, and then join
那个数组最多组成一个新的字符串。
const arr = ["hello", "there"];
const str = `'${arr.map(el => `"${el}"`).join(', ')}'`;
console.log(str);