【问题标题】:How to extract part of URL path and send URL onClick to query parameters如何提取部分 URL 路径并将 URL onClick 发送到查询参数
【发布时间】:2021-12-19 15:37:49
【问题描述】:

在我的在线艺术品商店中,我正在努力实现以下目标:

  • 产品页面上有一个“联系我”按钮,我希望该按钮从 URL 中检索艺术家的姓名并将其插入到按钮 URL 中。产品页面的 URL 结构:“https://store.com/product/smith-john-painting-1/”。

此时的结果:点击此页面上的“联系我”按钮将访问者带到“https://store.com/contact/smith-john/”

  • 另外,当访问者通过产品页面访问联系页面并填写联系表格时,我想知道他们查看了哪些产品。一种干净的方法(正如我从研究中了解到的)是使用查询参数。因此,使用上面提到的例子:当访问者查看产品页面并点击“联系我”按钮时,从URL中提取艺术家姓名(无论多长)“painting-1”之后的部分并添加作为“?product=painting-1”的查询参数。

最终结果:点击上述产品页面上的“联系我”按钮将引导访问者 “https://store.com/contact/smith-john/?product=painting-1”

我只找到了部分解决方案,有什么想法可以实现吗?

【问题讨论】:

标签: javascript url onclick query-parameters


【解决方案1】:

试试这个

const url = new URL("https://store.com/product/smith-john-painting-1/")
const artistUrl = url.origin

const parts = url.pathname.split("/")
const [lastName, firstName, item, number] = parts[2].split("-")
const pageUrl = `${artistUrl}/contact/${lastName}-${firstName}/?product=${item}-${number}`
console.log(pageUrl)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-11
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 2018-10-08
    • 2013-11-27
    • 2021-04-21
    相关资源
    最近更新 更多