如何在JavaScript教程中对URL进行编码?

JavaScript编程语言提供了不同的编码函数,但有些差别。这些函数可用于对URL进行编码。编码URL有助于防止错误,尤其是在传输过程中。编码URL将使URL仅由UTF-8字符组成。例如,空间、Tilda等可以通过编码以适当的方式表示。

null

JavaScript编码函数

JavaScript提供3种编码功能。这些功能可根据情况使用。

  • `逃逸`
  • `encodeURI()`
  • `编码器组件()`

使用escape()函数编码

escape() 是JavaScript版本1.5中不推荐使用的最简单的函数。它主要用于编码字符串。 * @ - _ + . / 不是由escape()函数编码的异常。因为escape()函数是非种族化的 encodeURI() encodeURIComponent() 而不是函数。

var char_set1 = ";,/?:@&=+$";  // Reserved Charactersvar char_set2 = "-_.!~*'()";   // Unescaped Charactersvar char_set3 = "#";           // Number Signvar char_set4 = "ABC abc 123"; // Alphanumeric Characters + Spacevar char_set5 = "poftut.com/about";  //Some normal URL to encodevar char_set6 = "İsmail Baydan" //Some nameescape(char_set1);escape(char_set2);escape(char_set3);escape(char_set4);escape(char_set5);escape(char_set6);
Encode with escape() Function
使用escape()函数编码

使用encodeURI()函数编码

encodeURI() 函数用于对统一资源标识符或URI进行编码,后者也可用于URL。

var char_set1 = ";,/?:@&=+$"; // Reserved Characters var char_set2 = "-_.!~*'()"; // Unescaped Characters var char_set3 = "#"; // Number Sign var char_set4 = "ABC abc 123"; // Alphanumeric Characters + Space var char_set5 = "poftut.com/about"; //Some normal URL to encode var char_set6 = "İsmail Baydan" //Some name encodeURI(char_set1);encodeURI(char_set2);encodeURI(char_set3);encodeURI(char_set4);encodeURI(char_set5);encodeURI(char_set6);
Encode with encodeURI() Function
使用encodeURI()函数编码

使用encodeURIComponent()函数编码

encodeURIComponent() 是另一个用于编码给定URL的函数。encodeURIComponent()函数对于编码URL更有用。encodeURIComponent()将正确编码&这可能会导致数据完整性受损。

var char_set1 = ";,/?:@&=+$"; // Reserved Characters var char_set2 = "-_.!~*'()"; // Unescaped Characters var char_set3 = "#"; // Number Sign var char_set4 = "ABC abc 123"; // Alphanumeric Characters + Space var char_set5 = "poftut.com/about"; //Some normal URL to encode var char_set6 = "İsmail Baydan" //Some name encodeURIComponent(char_set1); encodeURIComponent(char_set2); encodeURIComponent(char_set3); encodeURIComponent(char_set4); encodeURIComponent(char_set5); encodeURIComponent(char_set6);
Encode with encodeURIComponent() Function
使用encodeURIComponent()函数编码

相关文章: URI和URL有什么区别?

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享