Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode URL in JavaScript?

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?

like image 694
nickf Avatar asked Dec 02 '08 02:12

nickf


People also ask

What is encode URI in JavaScript?

The encodeURI() function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

How do I encode a URL?

URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits. URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.

How do you decode or encode a URL in JavaScript?

Decoding in Javascript can be achieved using decodeURI function. It takes encodeURIComponent(url) string so it can decode these characters. 2. unescape() function: This function takes a string as a single parameter and uses it to decode that string encoded by the escape() function.

What is encoding in JavaScript?

A string is a series of bytes. A byte is 8 bits, each of which can be 0 or 1, so a byte can have 28 or 256 different values. Encoding is the process of squashing the graphics you see on screen, say, 世 - into actual bytes.


1 Answers

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); 
like image 75
Buu Nguyen Avatar answered Sep 30 '22 12:09

Buu Nguyen