URL编码和解码

1、escape 和 unescape

escape不能直接用于URL的编码。真正的作用是返回一个字符的Unicode编码值。(不属于对URL的编码,属于对字符编码)

var a  = escape("你好,JS");
// "%u4F60%u597D%uFF0CJS"

unescape解码

var b = unescape("%u4F60%u597D%uFF0CJS");//"你好,JS"

2、encodeURI 和 decodeURI

encodeURI把字符串采用UTF-8编码格式转化为escape格式的字符串。

var url = "http://localhost:8080/home?a=张三";
encodeURI(url)  -->   http://localhost:8080/home?a=%E5%BC%A0%E4%B8%89

 

 decodeURI把escape格式的字符串转化为原始的字符串。

var url = "http://localhost:8080/home?a=张三";
encodeURI(url)  -->   http://localhost:8080/home?a=%E5%BC%A0%E4%B8%89

 decodeURI把escape格式的字符串转化为原始的字符串。

decodeURI("http://localhost:8080/home?a=%E5%BC%A0%E4%B8%89") -->
http://localhost:8080/home?a=张三

 

3、encodeURIComponent 和 decodeURIComponent

encodeURIComponent和encodeURI都是对URL编码。 ,不同的是编码的字符范围不一样

encodeURI方法不会对下列字符编码   ASCII字母、数字、~!@#$&*()=:/,;?+'

encodeURIComponent方法不会对下列字符编码  ASCII字母、数字、~!*()'

所以encodeURIComponent比encodeURI编码的范围更大。

实际例子来说,encodeURIComponent会把 http:// 编码成 http%3A%2F%2F 而encodeURI却不会。

使用场合

1、如果只是编码字符串,和URL无关,用escape

2、如果你需要编码整个URL,然后需要使用这个URL,那么用encodeURI。

3、当你需要编码URL中的参数的时候,使用encodeURIComponent。

 

在VB6(Visual Basic 6)中,URL编码解码是常见的需求,特别是在处理网页数据或进行网络请求时。URL编码是将特殊字符转换为可以在URL中安全传输的格式,而URL解码则是将编码后的字符串转换回原始格式。 ### URL编码 在VB6中,可以使用`Server.URLEncode`方法进行URL编码。这个方法通常在ASP页面中使用,但也可以在VB6的COM组件中使用。 ```vb Function URLEncode(ByVal StringVal As String) As String Dim i As Long Dim CharVal As Integer Dim EncodedStr As String For i = 1 To Len(StringVal) CharVal = Asc(Mid$(StringVal, i, 1)) Select Case CharVal Case 48 To 57, 65 To 90, 97 To 122 ' 0-9, A-Z, a-z EncodedStr = EncodedStr & Chr$(CharVal) Case 32 ' Space EncodedStr = EncodedStr & "+" Case Else EncodedStr = EncodedStr & "%" & Hex$(CharVal) End Select Next i URLEncode = EncodedStr End Function ``` ### URL解码 在VB6中,可以使用`Server.URLDecode`方法进行URL解码。同样,这个方法通常在ASP页面中使用,但也可以在VB6的COM组件中使用。 ```vb Function URLDecode(ByVal StringVal As String) As String Dim i As Long Dim CharVal As Integer Dim DecodedStr As String For i = 1 To Len(StringVal) CharVal = Asc(Mid$(StringVal, i, 1)) Select Case CharVal Case 43 ' + DecodedStr = DecodedStr & " " Case 37 ' % DecodedStr = DecodedStr & Chr$(Val("&H" & Mid$(StringVal, i + 1, 2))) i = i + 2 Case Else DecodedStr = DecodedStr & Chr$(CharVal) End Select Next i URLDecode = DecodedStr End Function ``` ### 使用示例 ```vb Sub TestURLEncodeDecode() Dim originalString As String Dim encodedString As String Dim decodedString As String originalString = "Hello World! 123" encodedString = URLEncode(originalString) decodedString = URLDecode(encodedString) MsgBox "Original: " & originalString MsgBox "Encoded: " & encodedString MsgBox "Decoded: " & decodedString End Sub ``` 通过上述代码,你可以看到如何进行URL编码解码,并验证其正确性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值