我想要实现这样的目标。如果我之前像这样输入
const partofurls = {
protocol: 'https',
host: 'hosturl',
port: 8080,
endpoint: 'someendpoint',
queryparams: {
key1:value1,
key2:value2
}
}
我想获取如下URL
https://hosturl:8080/endpoint?key1=value1&key2=value2
在javascript或reactjs中有什么方法可以实现这一点吗?
我从用户那里获取这些字段。如果用户在主机 URL 的末尾添加了斜杠“/”,并且在端点的开头也添加了“/”,那么我最终会在主机 URL 和端点之间添加两个斜杠。类似这样的例子还有很多。
为了解决所有这些问题,reactjs或javascript中是否有可用的标准模块或库?
最佳答案
你可以构建这样的东西
const urlObj = {
protocol: 'https',
host: 'hosturl',
port: 8080,
endpoint: 'someendpoint',
queryparams: {
key1: 'value1',
key2: 'value2'
}
}
let { protocol, host, port, endpoint, queryparams } = urlObj
let encodeQuery = new URLSearchParams(queryparams).toString()
let url = `${protocol}://${host}:${port}/${endpoint}?${encodeQuery}`
console.log(url)
关于javascript - Reactjs 使用字符串的不同部分构建 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58211330/