在PHP或Javascript中从url读取/获取@ value

4sup72z8  于 2023-01-16  发布在  PHP
关注(0)|答案(1)|浏览(123)

我目前正在开发一个站点,用户可以在其中使用注册时创建的用户目录(如myWebsite.com/user/myUserName)创建用户区域
现在我看到YouTube和TikTok(可能还有更多)使用myWebsite.com/user/@myUserName这样的网址(注意“@”)
所以我的问题是我如何读取这些?如果用户访问myWebsite.com/user/@myUserName,我如何读取@数据?
我已经搜索了许多这样的问题和谷歌之前,问这个,不能看到找到答案。只有标准的网址参数或标签,但没有@,帮助!

llmtgqce

llmtgqce1#

溶液
可以使用window.location.pathname API读取路径名,将其解析为数组,然后过滤掉唯一以"@"字符开头的项。

// take the entire path from the window and split them into an array with /
const paths = window.location.pathname.split('/')
// paths = ["","user","@myUserName"]

// pick out the first item in the array starting with an "@:
const userName = paths.find((item) => item.at(0) === "@")
// userName = "@myUserName"

解释

首先,您需要了解URL https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL的结构
在您的示例中,用户ID应该是路径的一部分,要获得/my-path/@user-id的完整路径,可以使用window.location.pathname(MDN reference)
从这里开始,您可以使用JavaScript解析路径以获取用户ID

备选答案

或者你可以直接使用正则表达式来捕获"@"后面的任何内容

const final = window.location.pathname.match("@.*").at(0)
// note: not a complete solution because it captures the other parts of the URL following the `/@username/` path

相关问题