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%2 F%34"
someFunction("hello 1,2 3/4") gives the string: "hello%20%31%2C%32%20%33%2
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
More info here: http://en.wikipedia.org/wiki/Percent-encoding
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.
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.
ASKER
Thanks. In the end, I decided to use escape() since it seemed to encode more.
ASKER
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?