Encode URL in JavaScript?
Encode URL in JavaScript?
Question
How do you safely encode a URL using JavaScript such that it can be put into a GET string?
var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var myOtherUrl = "http://example.com/index.html?url=" + myUrl;
I assume that you need to encode the myUrl
variable on that second line?
Accepted Answer
Check out the built-in function encodeURIComponent(str) and encodeURI(str).
In your case, this should work:
var myOtherUrl =
"http://example.com/index.html?url=" + encodeURIComponent(myUrl);
Popular Answer
You have three options:
escape()
will not encode:@*/+
encodeURI()
will not encode:[email protected]#$&*()=:/,;?+'
encodeURIComponent()
will not encode:~!*()'
But in your case, if you want to pass a URL into a GET
parameter of other page, you should use escape
or encodeURIComponent
, but not encodeURI
.
See Stack Overflow question Best practice: escape, or encodeURI / encodeURIComponent for further discussion.
Read more… Read less…
Stick with encodeURIComponent()
. The function encodeURI()
does not bother to encode many characters that have semantic importance in URLs (e.g. "#", "?", and "&"). escape()
is deprecated, and does not bother to encode "+" characters, which will be interpreted as encoded spaces on the server (and, as pointed out by others here, does not properly URL-encode non-ASCII characters).
There is a nice explanation of the difference between encodeURI()
and encodeURIComponent()
elsewhere. If you want to encode something so that it can safely be included as a component of a URI (e.g. as a query string parameter), you want to use encodeURIComponent()
.
The best answer is to use encodeURIComponent
on values in the query string (and nowhere else).
However, I find that many APIs want to replace " " with "+" so I've had to use the following:
const value = encodeURIComponent(value).replace('%20','+');
const url = 'http://example.com?lang=en&key=' + value
escape
is implemented differently in different browsers and encodeURI
doesn't encode many characters (like # and even /) -- it's made to be used on a full URI/URL without breaking it – which isn't super helpful or secure.
And as @Jochem points out below, you may want to use encodeURIComponent()
on a (each) folder name, but for whatever reason these APIs don't seem to want +
in folder names so plain old encodeURIComponent
works great.
Example:
const escapedValue = encodeURIComponent(value).replace('%20','+');
const escapedFolder = encodeURIComponent('My Folder'); // no replace
const url = `http://example.com/${escapedFolder}/?myKey=${escapedValue}`;
If you are using jQuery I would go for $.param
method. It URL encodes an object mapping fields to values, which is easier to read than calling an escape method on each value.
$.param({a:"1=2", b:"Test 1"}) // gets a=1%3D2&b=Test+1
encodeURIComponent() is the way to go.
var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl);
BUT you should keep in mind that there are small differences from php version urlencode()
and as @CMS mentioned, it will not encode every char. Guys at http://phpjs.org/functions/urlencode/ made js equivalent to phpencode()
:
function urlencode(str) {
str = (str + '').toString();
// Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
// PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
return encodeURIComponent(str)
.replace('!', '%21')
.replace('\'', '%27')
.replace('(', '%28')
.replace(')', '%29')
.replace('*', '%2A')
.replace('%20', '+');
}
To encode a URL, as has been said before, you have two functions:
encodeURI()
and
encodeURIComponent()
The reason both exist is that the first preserves the URL with the risk of leaving too many things unescaped, while the second encodes everything needed.
With the first, you could copy the newly escaped URL into address bar (for example) and it would work. However your unescaped '&'s would interfere with field delimiters, the '='s would interfere with field names and values, and the '+'s would look like spaces. But for simple data when you want to preserve the URL nature of what you are escaping, this works.
The second is everything you need to do to make sure nothing in your string interfers with a URL. It leaves various unimportant characters unescaped so that the URL remains as human readable as possible without interference. A URL encoded this way will no longer work as a URL without unescaping it.
So if you can take the time, you always want to use encodeURIComponent() -- before adding on name/value pairs encode both the name and the value using this function before adding it to the query string.
I'm having a tough time coming up with reasons to use the encodeURI() -- I'll leave that to the smarter people.