【问题标题】:Convert array to string while preserving the quotes around the elements将数组转换为字符串,同时保留元素周围的引号
【发布时间】: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


【解决方案1】:

您可以简单地使用join()template literals

function convert(arrData) {
  return `'"${arrData.join('", "')}"'`;
}

const a = ["hello", "there"];

console.log(convert(a));

【讨论】:

    【解决方案2】:

    map 覆盖元素并从中创建an array of strings,然后join 该数组向上形成一个新字符串。

    const arr = ["hello", "there"];
    const str = `'${arr.map(el => `"${el}"`).join(', ')}'`;
    console.log(str);

    【讨论】:

    • 他需要这样'"hello", "there"'
    猜你喜欢
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-10
    • 2017-06-19
    • 1970-01-01
    • 2019-02-21
    相关资源
    最近更新 更多