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

safeEncodeURIComponent

Safely encodes a URI component with a fallback on failure.

TypeScript
Copied!
1/**
2 * Safely encodes a URI component with a fallback on failure.
3 *
4 * @param str - The input string to encode.
5 * @param fallback - Optional fallback string if encoding fails.
6 * @returns Encoded string or fallback value.
7 */
8export function safeEncodeURIComponent(str: string, fallback = ''): string {
9  try {
10    return encodeURIComponent(str);
11  } catch {
12    return fallback;
13  }
14}
  • Graceful Failure Handling

    Prevents runtime crashes by catching exceptions from encodeURIComponent and returning a fallback value.

  • Safe for Untrusted Input

    Can be used with unpredictable or user-generated strings without risking malformed output or errors.

  • Customizable Fallback

    Allows developers to specify a default return value, making behavior predictable in failure scenarios.

  • Minimal Overhead

    Lightweight wrapper over a native function with negligible performance cost and no dependencies.

Tests | Examples

TypeScript
Copied!
1test('safeEncodeURIComponent - encodes standard string', () => {
2  expect(safeEncodeURIComponent('hello world')).toBe('hello%20world');
3});
4
5test('safeEncodeURIComponent - encodes special characters', () => {
6  expect(safeEncodeURIComponent('a+b=c&d')).toBe('a%2Bb%3Dc%26d');
7});
8
9test('safeEncodeURIComponent - works with unicode characters', () => {
10  expect(safeEncodeURIComponent('Привет')).toBe('%D0%9F%D1%80%D0%B8%D0%B2%D0%B5%D1%82');
11});
12
13test('safeEncodeURIComponent - returns fallback on error', () => {
14  const circular: any = {};
15  circular.self = circular;
16  expect(safeEncodeURIComponent(circular, 'fallback')).toBe('fallback');
17});
18
19test('safeEncodeURIComponent - empty string returns empty string', () => {
20  expect(safeEncodeURIComponent('')).toBe('');
21});

Common Use Cases

  • Building Query Strings or URLs

    Encode user input for use in URL parameters safely, avoiding malformed URIs.

  • Client-Side Navigation Helpers

    Safely encode path segments or search parameters for use in routing libraries.

  • Search Term Encoding

    Normalize search inputs before passing them to remote APIs.

  • Logging or Analytics

    Encode raw strings for transmission in URLs or beacon requests without interruption on failure.

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