Say I have a string like
JavaScript
x
2
1
http://somerandomwebsite.com/345345/465645456546
2
This string matches the pattern
JavaScript
1
2
1
http://somerandomwebsite.com/:userId/:gameId
2
From the above string, how do I extract the userId and gameId values no matter their length(so not substring)
I know in ExpressJS you can do
JavaScript
1
5
1
app.get("/:userId/:gameId", (req, res) => {
2
var userId = req.params.userId
3
var gameId = req.params.gameId
4
})
5
But I need this to work in client side Javascript
Is there any way to do this?
Advertisement
Answer
The URL API is a safe and modern method that works server and client side:
location.pathname
can be used if it is the url of the page you are on
link.pathname
can be used for link objects
Say I have a string – then you need to make it a URL first
JavaScript
1
3
1
const [_,userID, gameID] = new URL("http://somerandomwebsite.com/345345/465645456546")
2
.pathname.split("/");
3
console.log(userID,gameID);