← Back to Guides
URL Encoding in JavaScript — encodeURI, encodeURIComponent, and Best Practices
· Tags: javascript, url-encoding, encodeURIComponent, encodeURI, programming
JavaScript provides two built-in functions for URL encoding:
encodeURIComponent()
Encodes all characters except: A-Z a-z 0-9 - _ . ! ~ * ' ( )
const name = 'John Doe'
const query = '?name=' + encodeURIComponent(name)
// ?name=John%20Doe
Use this for encoding individual query parameter values, path segments, or any data that becomes part of a URL.
encodeURI()
Encodes all characters except the above plus reserved URL characters: : / ? # [ ] @ ! $ & ' ( ) * + , ; =
const url = 'https://example.com/search?q=hello world'
const encoded = encodeURI(url)
// https://example.com/search?q=hello%20world
Use this when encoding a complete URL string.
Common Pitfall
// WRONG — breaks the URL structure
encodeURIComponent('https://example.com/page')
// https%3A%2F%2Fexample.com%2Fpage
// RIGHT — preserves structure
encodeURI('https://example.com/page')
// https://example.com/page
Test these functions live with our URL encoder/decoder tool.