Is there something like a replacePathParameters method?

Hello, I'm trying to do something like this with the SolidJS router:
replacePathParameters("/dogs/are/:var1/cats/are/:var2", {
"var1": "good",
"var2": "better",
});
replacePathParameters("/dogs/are/:var1/cats/are/:var2", {
"var1": "good",
"var2": "better",
});
Thanks for any help. 😄
4 Replies
BasicBit | Alex
BasicBit | AlexOP•16mo ago
The result should be "/dogs/are/good/cats/are/better" in that case. Thank you 😄
Max
Max•16mo ago
or if you dont speak regex 🤣
const replacePathParams = (
path: string,
params: Record<string, string | number | boolean>
) =>
Object.entries(params).reduce(
(path, [k, v]) => path.replace(`:${k}`, encodeURIComponent(v)),
path
);
const replacePathParams = (
path: string,
params: Record<string, string | number | boolean>
) =>
Object.entries(params).reduce(
(path, [k, v]) => path.replace(`:${k}`, encodeURIComponent(v)),
path
);
BasicBit | Alex
BasicBit | AlexOP•16mo ago
I speak regex but I like your solution more. It looks cleaner. 😂
Max
Max•16mo ago
shit yea didnt even think bout that sorting fairly simple but probably this works too
(path, [k, v]) => path.replace(`:${k}/`, `${encodeURIComponent(v)}/`),
(path, [k, v]) => path.replace(`:${k}/`, `${encodeURIComponent(v)}/`),
but then expects trailing / so sorting probably easier
Want results from more Discord servers?
Add your server