escaping special character in a url

前端 未结 2 1078
予麋鹿
予麋鹿 2020-12-06 07:53

I am using a url to open a html page, and i am sending data in querystring withe the page url.

For example: abc.html?firstParameter=firstvalue&seconedParam

相关标签:
2条回答
  • 2020-12-06 08:03

    You have 3 options:

    escape() will not encode: @*/+
    
    encodeURI() will not encode: ~!@#$&*()=:/,;?+'
    
    encodeURIComponent() will not encode: ~!*()'
    

    But in your case, if you want to pass a url into a GET parameter of other page, you should use escape or encodeURIComponent, but not encodeURI.

    0 讨论(0)
  • 2020-12-06 08:17

    To be safe and ensure that you've escaped all the reserved characters specified in both RFC 1738 and RFC 3986 you should use a combination of encodeURIComponent, escape and a replace for the asterisk('*') like this:

    encoded = encodeURIComponent( parm ).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
    

    [Explanation] While RFC 1738: Uniform Resource Locators (URL) specifies that the *, !, ', ( and ) characters may be left unencoded in the URL,

    Thus, only alphanumerics, the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL.

    RFC 3986, pages 12-13, states that these special characters are reserved as sub-delimiters.

    reserved = gen-delims / sub-delims

    gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"

    sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="

    The escape() function has been deprecated but can be used to URL encode the exclamation mark, single quote, left parenthesis and right parenthesis. And since there is some ambiguity on whether an asterisk must be encoded in a URL, and it doesn't hurt to encode, it you can explicitly encode is using something like the replace() function call. [Note that the escape() function is being passed as the second parameter to the first replace() function call. As used here, replace calls the escape() function once for each matched special character of !, ', ( or ), and escape merely returns the 'escape sequence' for that character back to replace, which reassembles any escaped characters with the other fragments.]

    Also see 'https://stackoverflow.com/questions/6533561/urlencode-the-asterisk-star-character'

    Also while some websites have even identified the asterkisk(*) as being a reserved character under RFC3986, they don't include it in their URL component encoding tool.

    Unencoded URL parms:

    parm1=this is a test of encoding !@#$%^&*()'
    parm2=note that * is not encoded
    

    Encoded URL parms:

    parm1=this+is+a+test+of+encoding+%21%40%23%24%25%5E%26*%28%29%27
    parm2=note+that+*+is+not+encodeds+not+encoded
    
    0 讨论(0)
提交回复
热议问题