Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split slugs in Svelte router in all possible options?

I want to build URL patter, like this [lang]/category/[name]-[suffix], where:

  • suffix is one of a few strings, for example: ['super-product', 'great-gadget', 'ta-ta-ta']
  • name is a multiple word slug, like a-bb-ccc

To implement it, I decided to use Matching:

export function match(param) {
  let result = /^(super-product|great-gadget|ta-ta-ta)/.test(param); 
  return a;
}

For the URL /en/category/a-bb-ccc-super-product/, param is bb-ccc-super-product. Q: How to make Svelte splits URL into slugs in all possible options, like: a + bb-ccc-super-product, a-bb + ccc-super-product, ..., a-bb-ccc-super + product, and not just in one a + bb-ccc-super-product?

Also, I tried to use handlers to resolve this issue, failed as I was not able to change URL.

  • "@sveltejs/kit": "1.0.0-next.310"
  • "svelte": "3.47.0"
like image 286
tarasinf Avatar asked Oct 31 '25 10:10

tarasinf


1 Answers

Short answer, you can't. Svelte will match like a non-greedy regular expression matcher, so in your case of [name]-[suffix], name will always hold whatever comes before the first matching hyphen (-) and suffix will hold whatever trails that first matching hyphen.

For reference, quoting the SvelteKit documentation (relevant bit bolded):

A route can have multiple dynamic parameters, for example src/routes/[category]/[item].svelte or even src/routes/[category]-[item].svelte. (Parameters are 'non-greedy'; in an ambiguous case like x-y-z, category would be x and item would be y-z.)

The easier solution would be for you to pick a different param separator like underscore (_), or a double-hyphen (--), or whatever sequence of characters you are positive will not appear within your params.

Alternatively, if you absolutely want, or need, to stick with your current naming scheme, it would be easier to treat it as a single param (name) and then parse this single param yourself using your own regular expression (as you have attempted, but mistakenly kept using 2 params).

like image 143
Thomas Hennes Avatar answered Nov 02 '25 23:11

Thomas Hennes