ARV*_*ARV 6 javascript url special-characters
我正在使用网址打开一个html页面,我正在使用页面网址以查询字符串发送数据.
例如: abc.html?firstParameter=firstvalue&seconedParameter=seconedvalue
问题是如果firstvalue或者secondvalue参数中包含特殊字符#,(,),%,{,那么我的网址构建不好.在这种情况下,url无法验证.我正在做这一切javascript.任何人都可以帮我解决这个问题.
Yog*_*ati 17
你有3个选择:
escape() will not encode: @*/+
encodeURI() will not encode: ~!@#$&*()=:/,;?+'
encodeURIComponent() will not encode: ~!*()'
Run Code Online (Sandbox Code Playgroud)
但在你的情况下,如果你想将url传递给其他页面的GET参数,你应该使用escape或encodeURIComponent,但不能使用encodeURI.
小智 6
为了安全并确保您已经转义了 RFC 1738 和 RFC 3986 中指定的所有保留字符,您应该使用 encodeURIComponent、escape 和替换星号('*')的组合,如下所示:
encoded = encodeURIComponent( parm ).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
Run Code Online (Sandbox Code Playgroud)
[说明] 虽然 RFC 1738: Uniform Resource Locators (URL) 指定 *、!、'、( 和 ) 字符可以保留在 URL 中未编码,
因此,只有字母数字、特殊字符“$-_.+!*'(),”和用于其保留目的的保留字符可以在 URL 中未编码地使用。
RFC 3986 第 12-13 页指出,这些特殊字符被保留为子分隔符。
保留 = gen-delims / sub-delims
gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
子delims =“!” / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
escape() 函数已被弃用,但可用于对感叹号、单引号、左括号和右括号进行 URL 编码。并且由于是否必须在 URL 中编码星号存在一些歧义,并且编码并没有什么坏处,因此您可以使用诸如 replace() 函数调用之类的方法进行显式编码。[请注意,escape() 函数作为第二个参数传递给第一个 replace() 函数调用。如此处所用,replace 为 !、'、( 或 ) 的每个匹配的特殊字符调用一次 escape() 函数,escape 仅返回该字符的“转义序列”以供替换,从而将任何转义字符与另一个重新组合片段。]
此外,虽然一些网站甚至将 asterkisk(*) 标识为 RFC3986 下的保留字符,但它们并未将其包含在其 URL 组件编码工具中。
未编码的 URL 参数:
parm1=this is a test of encoding !@#$%^&*()'
parm2=note that * is not encoded
Run Code Online (Sandbox Code Playgroud)
编码的 URL 参数:
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
Run Code Online (Sandbox Code Playgroud)