Skip to content

encodeUrl

Percent-encodes the symbols that break a URL: backslashes, spaces and the control characters. Every other character — including non-ASCII ones and a literal % — is left as is, so the result stays readable.

A literal % is only encoded when shouldEncodePercent is set. Leaving it alone is the default because it keeps the encoding idempotent for already-encoded input; the cost is that a path which genuinely contains % (a folder actually named a%20b) decodes back to something else. Turn the flag on whenever the input is a raw filesystem path that may contain %.

Import:

import { encodeUrl } from 'obsidian-dev-utils/url';

Example:

encodeUrl(String.raw`path\to the\file.md`) // 'path%5Cto%20the%5Cfile.md'
encodeUrl('a%20b') // 'a%20b'
encodeUrl('a%20b', true) // 'a%2520b'

Signature:

function encodeUrl(url: string, shouldEncodePercent: boolean | undefined): string

Parameters:

ParameterTypeDescription
urlstringThe URL to encode.
shouldEncodePercentboolean | undefinedWhether to encode a literal % as %25. Defaults to false.

Returns: string — The encoded URL.

Example:

encodeUrl(String.raw`path\to the\file.md`) // 'path%5Cto%20the%5Cfile.md'
encodeUrl('a%20b') // 'a%20b'
encodeUrl('a%20b', true) // 'a%2520b'

Links to this page: