HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

Encode URL in JavaScript

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
urljavascriptencode

Problem

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?

Solution

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

Code Snippets

var myOtherUrl = 
       "http://example.com/index.html?url=" + encodeURIComponent(myUrl);

Context

Stack Overflow Q#332872, score: 3238

Revisions (0)

No revisions yet.