Reputation: 153
So let's say I want to handle a URL, and I need an algorithm to get a data from my link.
My url has this shape: myapp://auth/userId/token
For example: myapp://auth/123/444444
How can I store 123 in a variable called userId
, and 444444 in a variable called token
?
Upvotes: 1
Views: 164
Reputation: 3214
Alternatively, you could use a RegEx and capture groups:
const myUrl = "myapp://auth/123/444444";
const regexpUrl = /^myapp:\/\/auth\/(?<userId>\w+)\/(?<token>\w+)/;
Usage:
const match = regexpUrl.exec(myUrl);
const extracted = { userId: match.groups.userId, token: match.groups.token };
You could also restrict the slugs to only digits with this pattern:
^myapp:\/\/auth\/(?<userId>\d+)\/(?<token>\d+)
Upvotes: 1
Reputation: 31992
Split it by /
and use Array.prototype.slice
to get the last 2 items.
const [userId, token] = "myapp://auth/123/444444".split('/').slice(3);
console.log(`userId=${userId}, token=${token}`);
Upvotes: 3
Reputation: 23664
You could use destructuring and Array.split().
let url="myapp://auth/123/444444"
const [channel, userid, token] = url.split("//")[1].split("/")
console.log(userid, token)
Upvotes: 1