简体   繁体   English

在客户端 Javascript 中获取请求参数

[英]Get req params in client Javascript

Say I have a string like说我有一个像

http://somerandomwebsite.com/345345/465645456546

This string matches the pattern此字符串与模式匹配

http://somerandomwebsite.com/:userId/:gameId

From the above string, how do I extract the userId and gameId values no matter their length(so not substring)从上面的字符串中,我如何提取 userId 和 gameId 值,无论它们的长度如何(所以不是子字符串)

I know in ExpressJS you can do我知道在 ExpressJS 中你可以做到

app.get("/:userId/:gameId", (req, res) => {
var userId = req.params.userId
var gameId = req.params.gameId
})

But I need this to work in client side Javascript但我需要它在客户端 Javascript 中工作

Is there any way to do this?有没有办法做到这一点?

The URL API is a safe and modern method that works server and client side: URL API是一种安全且现代的方法,适用于服务器端和客户端:

location.pathname can be used if it is the url of the page you are on如果location.pathname是您所在页面的 url,则可以使用它

link.pathname can be used for link objects link.pathname可用于链接对象

Say I have a string - then you need to make it a URL first假设我有一个字符串- 那么你需要先把它变成一个 URL

 const [_,userID, gameID] = new URL("http://somerandomwebsite.com/345345/465645456546") .pathname.split("/"); console.log(userID,gameID);

您可以使用window.location.pathname来获取 url 的路径名。

window.location.pathname.split('/')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM