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.
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>
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.
encodeURIComponent() twice turns %20 into %2520, breaking backend routing.encodeURI() for user query values: encodeURI("a&b") leaves & unencoded and splits your parameter.href paths: Avoid spaces in filenames altogether—name files html-guide.html instead of html guide.html.Standard path segments and encodeURIComponent() encode spaces as %20, while traditional HTML form query strings encode spaces as +.
Yes. When a visitor submits a form using method="get", the browser automatically URL-encodes every field name and value.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.