unicode编码相互转换加密解密
需求:把字符串转换成unicode编码加密。
也可以把unicode编码解密并分析出汉字字母数字字符各多少个。
unicode编码 \u 后面是一个16进制编码,必要时需要进行转换。
看源码:
| 0 | <!DOCTYPE html> |
| 1 | <html lang="en"> |
| 2 | <head> |
| 3 | <meta charset="UTF-8"> |
| 4 | <title>Document</title> |
| 5 | <style> |
| 6 | *{ |
| 7 | margin: 0; |
| 8 | padding: 0; |
| 9 | } |
| 10 | body{ |
| 11 | height: 5000px; |
| 12 | } |
| 13 | p{ |
| 14 | color: green; |
| 15 | font-size: 20px; |
| 16 | } |
| 17 | </style> |
| 18 | </head> |
| 19 | <body> |
| 20 | <input type="text"> |
| 21 | <button class="jm">加密</button> |
| 22 | <button class="dm">解密</button> |
| 23 | <p></p> |
| 24 | <script> |
| 25 | var ipt = document.querySelector('input'), |
| 26 | jm = document.querySelector('.jm'), |
| 27 | dm =document.querySelector('.dm'), |
| 28 | p = document.querySelector('p'); |
| 29 | jm.addEventListener('click', function(){ |
| 30 | var iptVal = ipt.value, |
| 31 | arr = [], |
| 32 | iptLength = iptVal.length |
| 33 | var i = 0; |
| 34 | for(i; i < iptLength; i += 1){ |
| 35 | arr[i] = ('00' + iptVal.charCodeAt(i).toString(16)).slice(-4); |
| 36 | } |
| 37 | var str = '\\u' + arr.join('\\u'); |
| 38 | p.innerHTML = str; |
| 39 | }) |
| 40 | |
| 41 | dm.addEventListener('click',function(){ |
| 42 | var iptVal = ipt.value, |
| 43 | i = 0, |
| 44 | str = iptVal.replace(/\\/g,'%'); |
| 45 | str = unescape(str), |
| 46 | strLength = str.length, |
| 47 | num = 0, |
| 48 | zi = 0, |
| 49 | mu = 0, |
| 50 | qi = 0, |
| 51 | Rnum = /[0-9]/, |
| 52 | Rzi = /[\u4e00-\u9fa5]/, |
| 53 | Rmu = /[A-Za-z]/; |
| 54 | |
| 55 | for(i; i < strLength; i += 1){ |
| 56 | if(Rnum.test(str[i])){ |
| 57 | num ++; |
| 58 | }else if (Rzi.test(str[i])) { |
| 59 | zi ++; |
| 60 | }else if (Rmu.test(str[i])) { |
| 61 | mu ++; |
| 62 | }else{ |
| 63 | qi ++; |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | p.innerHTML = '字符串总长度:' + strLength + ',字母' + mu + '个,汉字' + zi + '个,数字' + num + '个,其他的有' + qi + '个。'; |
| 68 | }) |
| 69 | </script> |
| 70 | </body> |
| 71 | </html> |

浙公网安备 33010602011771号