Encode URL in JavaScript?

ID : 252

viewed : 180

Tags : javascripturlencodeurlencodejavascript





Top 5 Answer for Encode URL in JavaScript?

vote vote

91

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); 
vote vote

82

You have three options:

  • escape() will not encode: @*/+

  • encodeURI() will not encode: ~!@#$&*()=:/,;?+'

  • 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.

vote vote

78

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().

vote vote

69

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}`; 
vote vote

58

I would suggest to use qs npm package

qs.stringify({a:"1=2", b:"Test 1"}); // gets a=1%3D2&b=Test+1 

it is easier to use with JS object and it gives you proper URL encoding for all parameters

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 

Top 3 video Explaining Encode URL in JavaScript?







Related QUESTION?