Many projects you'll work on, will require you to dynamically create URL routes. And this means you'll often need to generate a string to create the URL route.
Often you’ll use the encodeURIComponent() when doing this, because this will ensure the URL you create will be understood by all servers and browsers.
The encodeURIComponent() method encodes a URI by replacing URL reserved characters with their UTF-8 encoding.
More specifically, this function replaces each instance of certain characters by one, two, three, or four escape sequences representing a UTF-8 encoding of the character.
A common issue where this is applicable is special characters and spaces.
URLs do not allow many special characters, like spaces or slashes. However, these special characters are part of life, so URL encoding was invented.
This is where the special characters are replaced by a token value, usually beginning with a % followed by a number. The number correlates to the ASCII character hex value, for example a space is converted to %20, an ! is converted to %21 and so on.
While most browsers will auto convert characters like spaces to the URL encoded value of %20 there are always exceptions. Fortunately browsers provide native URL encoding and decoding functions, and one of these that we’ve just looked at is the encodeURIComponent() method.
Bottom line: This function is very useful when you want to encode query string parameters, for example when a user submits form data via a GET request.
Whew.
We've covered a lot in this short section. Don't worry if some of the concepts are little confusing or difficult. That is entirely normal. Just keep going with the course and it'll make more sense.
WELL DONE.