How to Fix Uncaught URIError: URI malformed Errors in JS

Ferenc Almasi β€’ 2022 July 11 β€’ Read time 2 min read
  • twitter
  • facebook
JavaScript

The "Uncaught URIError: URI malformed" error occurs in JavaScript, whenever you try to encode or decode a string that contains an invalid character. This results in unsuccessful encoding/decoding that can cause this error. Take the following as an example:

Copied to clipboard!
// ❌ This will throw "Uncaught URIError: URI malformed"
encodeURI('\uD800')

Why is the error happening?

Here we are trying to encode an invalid Unicode character. The reason this is invalid for encoding is that the Unicode code range starting from U+D800 (also called "high surrogate") can be combined with another Unicode range ending with U+DFFF (also called "low surrogate") to generate new characters.

In the above example, we are missing one of the pairs from a high-low pair, meaning we will get the above error, as it is seen as an invalid character. If we were to include the low pair too, we will have no problem with the encoding.

Copied to clipboard!
// βœ”οΈ This include both pairs, hence this will not produce an error
encodeURI('\uD800\uDFFF')

<- '%F0%90%8F%BF'

How to fix the error

In order to fix "Uncaught URIError: URI malformed" errors in your code, you need to ensure that you are passing valid characters to both encodeURI and decodeURI too. If you would like to convert Unicode code points to UTF8, you can use this online tool.

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.