You can use the built-in method encodeURIComponent() to safely encode a URL in JavaScript.
The encodeURIComponent() method encode all characters except the following:
A-Z a-z 0-9 - _ . ! ~ * ' ( )
Let's check out an example to understand how this method basically works:
<script>
// URL unsafe string
var item = "$url+/unsafe@item #name;"
// Encode item name and append to URL
var url = "http://example.com/search.php?product=" + encodeURIComponent(item);
document.write(url);
// Prints: http://example.com/search.php?product=%24url%2B%2Funsafe%40item%20%23name%3B
</script>
You can alternatively use the encodeURI() method, which does not encode characters that have special meaning (reserved characters) for a URI e.g. #, /, ?, etc.
The encodeURI() method encode all characters except the following:
Use the
encodeURIComponent()MethodYou can use the built-in method
encodeURIComponent()to safely encode a URL in JavaScript.The
encodeURIComponent()method encode all characters except the following:Let's check out an example to understand how this method basically works:
You can alternatively use the encodeURI() method, which does not encode characters that have special meaning (reserved characters) for a URI e.g. #, /, ?, etc.
The encodeURI() method encode all characters except the following:
The following example demonstrates how this method actually works:
need an explanation for this answer? contact us directly to get an explanation for this answer