Rules Hub
Coding Rules Library
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
Prefer URL object for query parameter construction
Use the native URL and URLSearchParams APIs to build query strings instead of manual string concatenation or array joining.
Bad example
| 1 | const rawUrl = 'https://example.com/resource'; |
| 2 | const category = 'News & Updates'; |
| 3 |
|
| 4 | // Bad: Manual encoding and string concatenation |
| 5 | const encodedUrl = encodeURIComponent(rawUrl); |
| 6 | const encodedCategory = encodeURIComponent(category); |
| 7 |
|
| 8 | const query = [ |
| 9 | 'id=123', |
| 10 | `u=${encodedUrl}`, |
| 11 | `cat=${encodedCategory}`, |
| 12 | 'type=article' |
| 13 | ].join('&'); |
| 14 |
|
| 15 | const finalUrl = `https://api.service.com/track?${query}`; |
Explanation (EN)
Manual string concatenation is brittle and error-prone. You must remember to manually encode every value using `encodeURIComponent`, and managing delimiters (`?`, `&`) becomes messy as complexity grows.
Objašnjenje (HR)
Ručno spajanje stringova je krhko i podložno greškama. Morate se sjetiti ručno kodirati svaku vrijednost koristeći `encodeURIComponent`, a upravljanje delimiterima (`?`, `&`) postaje neuredno kako složenost raste.
Good example
| 1 | const rawUrl = 'https://example.com/resource'; |
| 2 | const category = 'News & Updates'; |
| 3 |
|
| 4 | // Good: URL API handles encoding and formatting automatically |
| 5 | const url = new URL('https://api.service.com/track'); |
| 6 |
|
| 7 | url.searchParams.set('id', '123'); |
| 8 | url.searchParams.set('u', rawUrl); |
| 9 | url.searchParams.set('cat', category); |
| 10 | url.searchParams.set('type', 'article'); |
| 11 |
|
| 12 | const finalUrl = url.toString(); |
Explanation (EN)
The `URL` and `URLSearchParams` APIs automatically handle proper URI encoding and delimiter placement. This results in cleaner, more readable code and eliminates common bugs like double-encoding or malformed query strings.
Objašnjenje (HR)
`URL` i `URLSearchParams` API-ji automatski rješavaju ispravno URI kodiranje i postavljanje delimitera. To rezultira čišćim, čitljivijim kodom i eliminira uobičajene greške poput dvostrukog kodiranja ili neispravnih query stringova.
Notes (EN)
Note: Do not manually `encodeURIComponent` when using `url.searchParams.set()`, as the method performs encoding automatically. Doing so would result in double encoding.
Bilješke (HR)
Napomena: Nemojte ručno koristiti `encodeURIComponent` kada koristite `url.searchParams.set()`, jer ta metoda automatski provodi kodiranje. To bi rezultiralo dvostrukim kodiranjem.