Skip to main content
urlFix runs decodeURIComponent on a URL and (optionally) replaces the first space with a chosen separator. Use it to render Persian Wikipedia / blog URLs in UI without the noisy %xx escapes.
The exported function is urlFix (lowercase u). The name is not URLfix.

Function

urlFix(url?: string, separator?: string): string | undefined
import { urlFix } from "@persian-tools/persian-tools";

urlFix(
	"https://fa.wikipedia.org/wiki/%D9%85%DA%A9%D8%A7%D9%86%DB%8C%DA%A9%20%DA%A9%D9%88%D8%A7%D9%86%D8%AA%D9%88%D9%85%DB%8C",
);
// "https://fa.wikipedia.org/wiki/مکانیک کوانتومی"

urlFix(
	"https://fa.wikipedia.org/wiki/%D9%85%DA%A9%D8%A7%D9%86%DB%8C%DA%A9%20%DA%A9%D9%88%D8%A7%D9%86%D8%AA%D9%88%D9%85%DB%8C",
	"_",
);
// "https://fa.wikipedia.org/wiki/مکانیک_کوانتومی"

urlFix(undefined); // undefined
urlFix(""); // undefined

Behaviour

  1. Falsy input → undefined.
  2. decodeURIComponent(url) — expands all %xx escapes, including UTF-8 multi-byte sequences for Persian and other non-ASCII characters.
  3. If separator is provided, the first space in the decoded URL is replaced with separator (single String.replace, not global).

Pitfalls

  • Separator replacement is single-shot. Only the first space is replaced. Subsequent spaces stay literal.
  • The result is NOT re-encoded. It’s human-readable but no longer a valid fetch target. Use it for display, logs, or slug input — keep the encoded form for HTTP requests.
  • decodeURIComponent throws on malformed percent-encoding (e.g. lone %, invalid UTF-8 bytes). Wrap in try/catch for untrusted input.
  • Returns undefined (not "") on falsy input. Type the call site accordingly: const pretty = urlFix(raw) ?? raw.

Source

src/modules/URLfix/index.ts · Tests: test/URLfix.spec.ts