说我有一个像这样的字符串
http://somerandomwebsite.com/345345/465645456546
此字符串与模式匹配
http://somerandomwebsite.com/:userId/:gameId
从上面的字符串中,无论长度如何,如何提取userId和gameId值(而不是子字符串)
我知道您可以在ExpressJS中完成
app.get("/:userId/:gameId", (req, res) => {
var userId = req.params.userId
var gameId = req.params.gameId
})
但是我需要这个才能在客户端Javascript中工作
有什么办法吗?
答案 0 :(得分:1)
URL API是一种适用于服务器端和客户端的安全且现代的方法:
如果 location.pathname
是您所在页面的网址,则可以使用
link.pathname
可用于链接对象
说我有一个字符串-那么您需要先将其设置为URL
const [_,userID, gameID] = new URL("http://somerandomwebsite.com/345345/465645456546")
.pathname.split("/");
console.log(userID,gameID);
答案 1 :(得分:0)
您可以使用window.location.pathname
来获取URL的路径名。
window.location.pathname.split('/')