For example '/mentor/33 is url'
I do this with regex: buildRegex('/mentor/:id');
'/mentor/:id' becomes '/mentor/[^/]'
const PATH_PARAM = {
PREFIX: ':',
REGEX_IDENTIFIER: '/:[^/] ',
REGEX_REPLACER: '/[^/] ',
};
private buildRegex(path: string) {
return this.ensureLeadingSlash(path).replace(
new RegExp(PATH_PARAM.REGEX_IDENTIFIER, 'g'),
PATH_PARAM.REGEX_REPLACER
);
}
How can I just to get back 33, so value from [^/]?
If I use this
private matchRegex(routeLink: string, routeRegex: string) {
const match = routeLink.match(new RegExp(routeRegex, "g"));
return match?.[0];
}
then I get back /mentor/33 and not 33. I am looking for generic approach.
CodePudding user response:
Surround the replaced pattern into a group, then reference that group instead of [0]
after matching. Whether the group should be part of the PATH_PARAM
or dynamically constructed whenever buildRegex
is called will depend on your circumstances and what exactly is dynamic.
Because you're only performing the match once, don't use the global flag.
const PATH_PARAM = {
PREFIX: ':',
REGEX_IDENTIFIER: '/:[^/] ',
REGEX_REPLACER: '/[^/] ',
};
const buildRegex = (path) => {
return path.replace(
new RegExp(PATH_PARAM.REGEX_IDENTIFIER),
`(?<pathinfo>${PATH_PARAM.REGEX_REPLACER})`
);
};
const pattern = buildRegex('/mentor/:id');
const matchRegex = (routeLink, routeRegex) => {
const match = routeLink.match(routeRegex);
return match?.groups.pathinfo;
}
console.log(matchRegex('/mentor/33', pattern));
If the leading /
is a problem, note that a /
is included in both your REGEX_IDENTIFIER
and REGEX_REPLACER
. Either slice the first character out afterwards, or change the REGEX_IDENTIFIER
and REGEX_REPLACER
to remove the slashes, or put the group into the PATH_PARAM
object itself instead of constructing it dynamically.
const PATH_PARAM = {
PREFIX: ':',
REGEX_IDENTIFIER: '/:[^/] ',
REGEX_REPLACER: '/(?<pathinfo>[^/] )',
};
const buildRegex = (path) => {
return path.replace(
new RegExp(PATH_PARAM.REGEX_IDENTIFIER),
PATH_PARAM.REGEX_REPLACER
);
};
const pattern = buildRegex('/mentor/:id');
const matchRegex = (routeLink, routeRegex) => {
const match = routeLink.match(routeRegex);
return match?.groups.pathinfo;
}
console.log(matchRegex('/mentor/33', pattern));