Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

safeDecodeURIComponent

Safely decodes a URI component with a fallback on failure.

TypeScript
Copied!
1/**
2 * Safely decodes a URI component with a fallback on failure.
3 *
4 * @param str - The input string to decode.
5 * @param fallback - Optional fallback value if decoding fails.
6 * @returns Decoded string or fallback.
7 */
8export function safeDecodeURIComponent(str: string, fallback = ''): string {
9  try {
10    return decodeURIComponent(str);
11  } catch {
12    return fallback;
13  }
14}
  • Prevents Application Crashes

    Wraps decodeURIComponent in a try-catch block to avoid unhandled exceptions from malformed input.

  • Reliable Fallback Behavior

    Returns a developer-defined fallback value when decoding fails, ensuring predictable output.

  • Safe for Unvalidated Data

    Can process potentially unsafe or externally supplied data without compromising application stability.

  • Tiny and Dependency-Free

    Provides robust functionality with minimal footprint and no reliance on external libraries.

Tests | Examples

TypeScript
Copied!
1test('safeDecodeURIComponent - decodes standard encoded string', () => {
2  expect(safeDecodeURIComponent('hello%20world')).toBe('hello world');
3});
4
5test('safeDecodeURIComponent - decodes special characters', () => {
6  expect(safeDecodeURIComponent('a%2Bb%3Dc%26d')).toBe('a+b=c&d');
7});
8
9test('safeDecodeURIComponent - decodes unicode characters', () => {
10  expect(safeDecodeURIComponent('%D0%9F%D1%80%D0%B8%D0%B2%D0%B5%D1%82')).toBe('Привет');
11});
12
13test('safeDecodeURIComponent - returns fallback on malformed input', () => {
14  expect(safeDecodeURIComponent('%E0%A4%A', 'fallback')).toBe('fallback');
15});
16
17test('safeDecodeURIComponent - empty string returns empty string', () => {
18  expect(safeDecodeURIComponent('')).toBe('');
19});

Common Use Cases

  • Decoding URL Parameters

    Safely decode values extracted from query strings or hash fragments.

  • Parsing User Input from URLs

    Handle user-supplied links or deep-link parameters without crashing on bad encoding.

  • Error-Tolerant Navigation

    Decode paths or IDs in client-side routing while preserving flow if corruption occurs.

  • Analytics or Logging Pipelines

    Safely decode incoming parameters from requests or tracking beacons before storing or processing.

Codebase: Utilities -> Encoding -> safeDecodeURIComponent | Yevhen Klymentiev