Secure URL encoding utility that safely encodes URLs to percent-encoded form while preserving already-encoded sequences
npx @tessl/cli install tessl/npm-encodeurl@2.0.0Encode URL is a secure URL encoding utility that safely converts URLs to percent-encoded form while preserving already-encoded sequences. Unlike the built-in encodeURI function, it provides enhanced safety by not throwing errors and correctly handling Unicode surrogate pairs, making it ideal for web applications processing user-controlled URLs.
npm install encodeurlvar encodeUrl = require('encodeurl');var encodeUrl = require('encodeurl');
// Encode a URL with user-controlled data
var userInput = '/search?q=hello world&category=test';
var safeUrl = encodeUrl(userInput);
console.log(safeUrl); // '/search?q=hello%20world&category=test'
// Already encoded sequences are preserved
var partiallyEncoded = '/path%20with%20spaces/more spaces';
var result = encodeUrl(partiallyEncoded);
console.log(result); // '/path%20with%20spaces/more%20spaces'
// Invalid percent sequences are encoded
var invalidEncoding = '/path%foo%bar';
var fixed = encodeUrl(invalidEncoding);
console.log(fixed); // '/path%25foo%bar'Encodes a URL to percent-encoded form, excluding already-encoded sequences.
/**
* Encode a URL to a percent-encoded form, excluding already-encoded sequences.
* This function will take an already-encoded URL and encode all the non-URL
* code points. This function will not encode the "%" character unless it is
* not part of a valid sequence (%20 will be left as-is, but %foo will
* be encoded as %25foo).
*
* This encode is meant to be "safe" and does not throw errors. It will try as
* hard as it can to properly encode the given URL, including replacing any raw,
* unpaired surrogate pairs with the Unicode replacement character prior to
* encoding.
*
* @param {string} url - The URL string to encode
* @return {string} The encoded URL string
*/
function encodeUrl(url);Parameters:
url (string): The URL string to encode. Non-string values are coerced to string using String(url)Returns:
Key Features:
%20 are left unchanged%foo become %25foo\, ^, |, [, and ]Character Handling:
%20!, #-;, =, ?-_, a-z, |, ~): PreservedencodeURI)Usage Examples:
// Basic URL encoding
encodeUrl('http://localhost/ snow.html');
// → 'http://localhost/%20snow.html'
// Preserves already-encoded sequences
encodeUrl('http://localhost/%20snow.html');
// → 'http://localhost/%20snow.html'
// Fixes invalid percent encoding
encodeUrl('http://localhost/%foo%bar');
// → 'http://localhost/%25foo%bar'
// Handles Unicode correctly
encodeUrl('http://localhost/\uD83D\uDC7B snow.html');
// → 'http://localhost/%F0%9F%91%BB%20snow.html'
// Preserves IPv6 notation
encodeUrl('http://[::1]:8080/foo/bar');
// → 'http://[::1]:8080/foo/bar'
// Handles unmatched surrogate pairs safely
encodeUrl('http://localhost/\uD83Dfoo\uDC7B');
// → 'http://localhost/%EF%BF%BDfoo%EF%BF%BD'