Link to home
Start Free TrialLog in
Avatar of Mark
Mark

asked on

how to encode form GET parameters in javascript

Is there a javascript function to encode strings to the format for passing as <form method=get> parameters? For example:

someFunction("hello 1,2 3/4")  gives the string: "hello%20%31%2C%32%20%33%2F%34"
ASKER CERTIFIED SOLUTION
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Mark
Mark

ASKER

Thanks, those functions look like what I need. However, your answers have created new questions. You've given me: escape(), encodeURI(), encodeURIComponent(). Why three functions? Surely they must be for different things, or one is more obsolecent than the other? If I pick "escape()" and I making the 'Deprecated' choice?

In examining the side-by-side chart in mcnute's reference, encodeURI() does not encode characters less than SPACE. Why would one ever use that function? Not encoding e.g. "&" would certainly mess up a parameter string.

escape() does not encode "+", "/" or "@". encodeURIComponent() does encode these three, but does not encode "~", "!", "'", ")", "(". These seem like rather deliberate choices for specific purposes. I am unclear as to which function is appropriate for URL parameter strings. I'm leaning toward using escape() since it encodes the most, but to I run a risk with e.g. an embedded "+" in my parameter string, or a "/" in a date string?

Thoughts?
Anything less than SPACE is a control character and not legal in a query string.  SPACE is encoded as %20 and "&" is %26 which is not less than SPACE.  I think encodeURIComponent(chr) is the most useful for your purposes.

More info here: http://en.wikipedia.org/wiki/Percent-encoding
Avatar of Mark

ASKER

OK, all good info. That last link (DaveBaldwin) had some explanation that answers my question about slashes in dates being passed as parameters:

In the "query" component of a URI (the part after a ? character), for example, "/" is still considered a reserved character but it normally has no reserved purpose, unless a particular URI scheme says otherwise. The character does not need to be percent-encoded when it has no reserved purpose.
Avatar of Mark

ASKER

Thanks. In the end, I decided to use escape() since it seemed to encode more.