Edward Tanoto
Edward Tanoto

Reputation: 153

How do I parse some data from a String, and store it to a variable

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

Answers (4)

zr0gravity7
zr0gravity7

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

Spectric
Spectric

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

Martes Carry
Martes Carry

Reputation: 41

Split it by character and work with array's indexes

Upvotes: 1

Kinglish
Kinglish

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

Related Questions