It seems like just about every project I work on needs to dynamically create url routes.
This means I need to use a value, more than likely a string, to create the route.
In a Single Page App the route is applied either as a hash fragment or queryString parameter.
A common issue 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: encodeURI, encodeURIComponent and decodeURI, decodeURIComponent. The question is how to use these functions and what the differences are between the Component and plain versions. First what each function does and how to use them.
URL encoding a value is simple, just call encodeURI, passing the string value you need to convert. The function returns the URL encoded value.
encodeURI("http://www.yourdomain.com/a file with spaces.html");
This works in reverse, taking an encodes string and replacing the tokens with the normal characters. Call decodeURI, passing the encoded string value you need to convert. The function returns the decoded, normal text value.
http://www.yourdomain.com/a file with spaces.html
The encodeURIComponent function should be used to encode queryString parameters, in particular URLs. The difference between encodeURI and encodeURIComponent is encodeURIComponent encodes the entire string, where encodeURI ignores protocol prefix ('http://') and domain name. encodeURIComponent is designed to encode everything, where encodeURI ignores a URL's domain related roots.
Use encodeURIComponent when you want to encode a URL parameter.param1 = encodeURIComponent("http://xyz.com/?a=12&b=55");
Then you may create the URL you need:url = "http://domain.com/?param1=" + param1 + "¶m2=99";
And you will get this complete URL:
Note that encodeURIComponent does not escape the ' character. A common bug is to use it to create html attributes such as href='MyUrl', which could suffer an injection bug. If you are constructing html from strings, either use " instead of ' for attribute quotes, or add an extra layer of encoding (' can be encoded as %27).
Again decodeURIComponent reverses a string's URL encoding and returns a normal text value.
var decoded = decodeURIComponent("http://www.domain.com/?param1=http%3A%2F%2Fxyz.com%2F%3Fa%3D12%26b%3D55¶m2=99");
which returns a decoded value of "http://www.domain.com/?param1=http://xyz.com/?a=12&b=55¶m2=99".