I have a web form that was written a while ago that I'm trying to interface with - I don't have access to change it. I need to be able to interface with it through javascript, but I'm struggling to get javascript to encode the data in the right way. It looks like EVERYTHING that is not [A-Za-z0-9] is encoded, but I can't find a javascript function that'll do the same thing. Test case:

Input: ~+@-="'()_ (there's a space at the end)

Desired output: %7E%2B%40%2D%3D%22%27%27%28%29%5F%20

escape: %7E+@-%3D%22%27%28%29_%20

encodeURI: ~+@-=%22'()_%20

encodeURIcomponent: ~%2B%40-%3D%22'()_%20

Note than I'm (shudder) using IE10. Also not changeable. (I'm no more happy about this than you are.)

Any suggestions? (Preferably vanilla)

有帮助吗?

解决方案

It looks as though it is the Hex equivalent

~       = 7E
+       = 2B
@       = 40
-       = 2D
=       = 3D
"       = 22
'       = 27
(       = 28
)       = 29
_       = 5F
space   = 20

You should be able to use to charCodeAt to encode these values

'~'.charCodeAt(0).toString(16).toUpperCase()
    // -> returns '7E'

Edit

• ASCII codes are here: http://www.ascii.cl/htmlcodes.htm

• string(16) means base 16, which is hexadecimal

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top