HTML URL Encode
HTML URL Encode: Passing Safe Characters in Web Addresses
URLs can safely transmit only a limited set of ASCII characters (letters, digits, -, _, ., and ~). Whenever a web address or query parameter contains spaces, non-English scripts, or reserved symbols like & and ?, browsers convert those characters into percent-encoded sequences (%XX) through URL encoding.
Why Reserved Characters Must Be Encoded
Characters such as ?, &, =, /, and # have special structural meanings inside a URL. If a user searches for C++ & HTML, leaving a raw & unencoded makes the server split the query at & and lose half the search phrase.
URL encoding replaces each unsafe byte with % followed by two hexadecimal digits—for instance, a space becomes %20 (or + inside application/x-www-form-urlencoded form query strings), & becomes %26, and + becomes %2B.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML URL Encoding Demo</title>
</head>
<body style="font-family: system-ui, sans-serif; padding: 20px;">
<label for="search-term">Search Query:</label>
<input id="search-term" type="text" value="C++ & HTML5">
<button id="build-url" type="button">Encode URL</button>
<p id="url-result"></p>
<script>
document.getElementById('build-url').addEventListener('click', () => {
const term = document.getElementById('search-term').value;
const url = 'https://example.com/search?q=' + encodeURIComponent(term);
document.getElementById('url-result').textContent = url;
});
</script>
</body>
</html>
encodeURI vs. encodeURIComponent
In JavaScript, encodeURI() encodes an entire URL while keeping :, /, ?, and & intact. Always use encodeURIComponent() when building individual query parameter values so user-entered & or = symbols get escaped properly.
Common Mistakes to Avoid
- Double-encoding already encoded URLs: Running
encodeURIComponent()twice turns%20into%2520, breaking backend routing. - Using
encodeURI()for user query values:encodeURI("a&b")leaves&unencoded and splits your parameter. - Leaving raw spaces in
hrefpaths: Avoid spaces in filenames altogether—name fileshtml-guide.htmlinstead ofhtml guide.html.
Frequently Asked Questions
Why do some URLs show + for spaces while others show %20?
Standard path segments and encodeURIComponent() encode spaces as %20, while traditional HTML form query strings encode spaces as +.
Does HTML automatically encode form inputs on GET submission?
Yes. When a visitor submits a form using method="get", the browser automatically URL-encodes every field name and value.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.
Test Your Knowledge
You've completed this section! Take a quick 5-question quiz to check your understanding.