【问题标题】:array of strings with string interpolation带有字符串插值的字符串数组
【发布时间】:2020-03-30 20:35:03
【问题描述】:

我有一个字符串数组,如下所示

const array = ["string1", "string2", "string3"];
const total = 10000;

我有一个带有如下字符串插值的 url

const url = `http://localhost:8080/total=${total}&array=${array}`

这让我回到了下面

http://localhost:8080/total=10000&array=[string1, string2, string3]

如何使字符串数组与 JS 的字符串插值一起使用。

预期结果应该类似于

http://localhost:8080/total=10000&array=["string1", "string2", "string3"]

感谢任何帮助

【问题讨论】:

  • 为什么要在 URL 中添加["string1", "string2", "string3"]?这是 URL 中一种非常罕见的值。
  • 是的,通常当您将 JSON 对象/数据发送到服务器时,您将发布它。如果您坚持使用 GET,您将使用 URL 参数(例如每个字符串的单独参数),然后可以将它们在服务器端解析回数组。
  • 这就是后端 url 的构建方式,我们无法控制
  • 呸。在这种情况下,正如 Ori Drori 所说,JSON.stringify 是正确的选择。

标签: javascript arrays string replace string-interpolation


【解决方案1】:

使用JSON.stringify()将数组转换为字符串:

const array = ["string1", "string2", "string3"];
const total = 10000;

const url = `http://localhost:8080/total=${total}&array=${JSON.stringify(array)}`

console.log(url)

作为noted by @avejidah,您可能需要使用encodeURIComponent() 来转义带有保留字符的字符串。非保留字符为A-Z a-z 0-9 - _ . ! ~ * ' ( ):

const array = ["string1", "string2", "string3"];
const total = 10000;

const url = `http://localhost:8080/total=${total}&array=${encodeURIComponent(JSON.stringify(array))}`

console.log(url)

【讨论】:

  • 您可能也想encodeURIComponent,因为字符串可能包含保留字符(点/斜杠/加号/等)。
猜你喜欢
  • 1970-01-01
  • 2015-09-11
  • 1970-01-01
  • 2020-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-19
相关资源
最近更新 更多