我目前正在开发一个站点,用户可以在其中使用注册时创建的用户目录(如myWebsite.com/user/myUserName
)创建用户区域
现在我看到YouTube和TikTok(可能还有更多)使用myWebsite.com/user/@myUserName
这样的网址(注意“@”)
所以我的问题是我如何读取这些?如果用户访问myWebsite.com/user/@myUserName
,我如何读取@数据?
我已经搜索了许多这样的问题和谷歌之前,问这个,不能看到找到答案。只有标准的网址参数或标签,但没有@,帮助!
1条答案
按热度按时间llmtgqce1#
溶液
可以使用
window.location.pathname
API读取路径名,将其解析为数组,然后过滤掉唯一以"@"字符开头的项。解释
首先,您需要了解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
备选答案
或者你可以直接使用正则表达式来捕获"@"后面的任何内容