How to URL encode a string in Ruby

后端 未结 8 803
醉梦人生
醉梦人生 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:25
    str = "\x12\x34\x56\x78\x9a\xbc\xde\xf1\x23\x45\x67\x89\xab\xcd\xef\x12\x34\x56\x78\x9a"
    require 'cgi'
    CGI.escape(str)
    # => "%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx%9A"
    

    Taken from @J-Rou's comment

    0 讨论(0)
  • 2020-12-02 06:25

    I was originally trying to escape special characters in a file name only, not on the path, from a full URL string.

    ERB::Util.url_encode didn't work for my use:

    helper.send(:url_encode, "http://example.com/?a=\11\15")
    # => "http%3A%2F%2Fexample.com%2F%3Fa%3D%09%0D"
    

    Based on two answers in "Why is URI.escape() marked as obsolete and where is this REGEXP::UNSAFE constant?", it looks like URI::RFC2396_Parser#escape is better than using URI::Escape#escape. However, they both are behaving the same to me:

    URI.escape("http://example.com/?a=\11\15")
    # => "http://example.com/?a=%09%0D"
    URI::Parser.new.escape("http://example.com/?a=\11\15")
    # => "http://example.com/?a=%09%0D"
    
    0 讨论(0)
提交回复
热议问题