Malformed URL Encoding Error
Fix malformed URL encoding errors when percent-encoded characters (%XX) are invalid or incomplete in URLs and query strings.
What Does This Error Mean?
A malformed URL encoding error occurs when a percent-encoded sequence (% followed by two hex digits) is incomplete, contains invalid hex characters, or is used in the wrong context. URLs must use proper percent-encoding for special characters.
Common Causes
Incomplete percent-encoded sequence (e.g., %2 instead of %20)
Invalid hex digits after % (e.g., %ZZ instead of %20)
Double-encoding a URL (e.g., %2520 instead of %20)
Mixed encoding schemes in the same URL string
Non-ASCII characters not percent-encoded in the URL
How to Fix It
Use encodeURIComponent() for query parameters
Always encode dynamic values before inserting them into URLs.
// ❌ Raw special characters
const url = `https://api.example.com/search?q=${userInput}`
// Fails if userInput contains &, ?, #, spaces
// ✅ Proper encoding
const url = `https://api.example.com/search?q=${encodeURIComponent(userInput)}`
// For full URLs, use encodeURI()
const fullUrl = encodeURI("https://example.com/path with spaces/file.html")Fix incomplete sequences
Ensure every % is followed by exactly two valid hex digits (0-9, A-F).
// ❌ Incomplete: %2 (missing second hex digit)
"file%2"
// ❌ Invalid hex: %GG (G is not hex)
"file%GG"
// ✅ Valid: %20 (space)
"file%20name"
// Fix function
function fixUrlEncoding(str) {
return str.replace(/%([0-9A-Fa-f]{0,1})(?![0-9A-Fa-f])/g, (match, hex) => {
return hex ? "%" + hex.padEnd(2, "0") : "%25"
})
}Avoid double-encoding
Do not encode an already-encoded URL again.
// ❌ Double encoding
const alreadyEncoded = "hello%20world"
const doubleEncoded = encodeURIComponent(alreadyEncoded)
// Result: "hello%2520world" (wrong!)
// ✅ Check if already encoded
function safeEncode(str) {
try {
return decodeURIComponent(str) !== str
? str // Already encoded
: encodeURIComponent(str)
} catch {
return encodeURIComponent(str)
}
}Related Tools
Use these tools to debug and fix this error:
Related Errors
Other common errors in this category: