Kevin AB
Kevin AB

Reputation: 583

get the names of all the secondary routes in a url in angular

the url is the following

http://localhost:4100/example/5b8c94cfc5f85728db8bddf2/5b8c94d0c5f85728db8bddf3/(p1:.....//p2:....//p3 ....),

I need to get p1, p2, p3, from any component, in this case.

I tried to put together a regular expression, but in the js console it fails me, however in https://regexr.com/ it works correctly.

I get the url of the Router class

let url = this.router.url;
let partial = this.router.url.split ('(') [1]

let regex = /(\w)*:/g
let outlets = regex.exec(partial)
console.log(outlets) // you do not get all the matches

I need to get all the names of the secondary outlets from any component, I thought in this way, I have problems in the regex.

If there were another way to get what I want, it would be very useful.

Upvotes: 0

Views: 86

Answers (1)

Obsidian Age
Obsidian Age

Reputation: 42314

What I would recommend is using a positive lookbehind on the ( character with /(?<=\().+/:

This can be seen working in the following:

const url = "http://localhost:4100/example/5b8c94cfc5f85728db8bddf2/5b8c94d0c5f85728db8bddf3/(p1:.....//p2:....//p3";
const regex = /(?<=\().+/;

console.log(url.match(regex)[0]);

Or if you want to capture all three groups individually, you can use
/(?<=\()(.+(?=\/\/))\/\/(.+(?=\/\/))\/\/(.+)/:

const url = "http://localhost:4100/example/5b8c94cfc5f85728db8bddf2/5b8c94d0c5f85728db8bddf3/(p1:.....//p2:....//p3";
const regex = /(?<=\()(.+(?=\/\/))\/\/(.+(?=\/\/))\/\/(.+)/;

console.log(url.match(regex));

This looks complex, but essentially does the same thing, simply with the addition of a lookahead on // and having that criteria repeated three times.

Upvotes: 1

Related Questions