How to URL encode a string in Ruby

后端 未结 8 859
醉梦人生
醉梦人生 2020-12-02 05:34

How do I URI::encode a string like:

\\x12\\x34\\x56\\x78\\x9a\\xbc\\xde\\xf1\\x23\\x45\\x67\\x89\\xab\\xcd\\xef\\x12\\x34\\x56\\x78\\x9a
         


        
8条回答
  •  孤街浪徒
    2020-12-02 06:20

    You can use Addressable::URI gem for that:

    require 'addressable/uri'   
    string = '\x12\x34\x56\x78\x9a\xbc\xde\xf1\x23\x45\x67\x89\xab\xcd\xef\x12\x34\x56\x78\x9a'
    Addressable::URI.encode_component(string, Addressable::URI::CharacterClasses::QUERY)
    # "%5Cx12%5Cx34%5Cx56%5Cx78%5Cx9a%5Cxbc%5Cxde%5Cxf1%5Cx23%5Cx45%5Cx67%5Cx89%5Cxab%5Cxcd%5Cxef%5Cx12%5Cx34%5Cx56%5Cx78%5Cx9a" 
    

    It uses more modern format, than CGI.escape, for example, it properly encodes space as %20 and not as + sign, you can read more in "The application/x-www-form-urlencoded type" on Wikipedia.

    2.1.2 :008 > CGI.escape('Hello, this is me')
     => "Hello%2C+this+is+me" 
    2.1.2 :009 > Addressable::URI.encode_component('Hello, this is me', Addressable::URI::CharacterClasses::QUERY)
     => "Hello,%20this%20is%20me" 
    

提交回复
热议问题