Encoding and Decoding Functions in JavaScript

  • 2021-07-21 06:59:57
  • OfStack

js involves three functions to encode characters: escape, encodeURI and encodeURIComponent, and corresponding three decoding functions: unescape, decodeURI and decodeURIComponent

1. Use encodeURIComponent when passing parameters, so that the combined url will not be truncated by special characters such as #.

For example:

2. encodeURI can be used as a whole when performing url jump

For example: Location.href=encodeURI ("http://cang.baidu.com/do/s? word= Baidu & ct=21");

3. escape can be used when js uses data

For example, history records in search of collections.

4. When escape encodes unicode values other than 0-255, it outputs% u**** format, and the encoding results of escape, encodeURI and encodeURIComponent are the same in other cases.

The most used should be encodeURIComponent, which converts Chinese, Korean and other special characters into url encoding in utf-8 format, so if you need to use encodeURIComponent to pass parameters to the background, you need background decoding to support utf-8 (the encoding mode in form is the same as the current page encoding mode)

There are 69 escape unencoded characters: *, +,-,.,/, @, _, 0-9, a-z, A-Z

encodeURI has 82 uncoded characters:! , #, $, & , ', (,), *, +,,,-,.,/,:,; , =,? , @, _, ~, 0-9, a-z, A-Z

There are 71 encodeURIComponent uncoded characters:! , ', (,), *,-,., _, ~, 0-9, a-z, A-Z

For the difference between escape, encodeURI and encodeURIComponent, see javascript characters Escape, encodeURI and encodeURIComponent here


Related articles: