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)
I know in ExpressJS you can do
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
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
const [_,userID, gameID] = new URL("http://somerandomwebsite.com/345345/465645456546") .pathname.split("/"); console.log(userID,gameID);