//字符串編碼轉為unicode編碼
function charToUnicode(str) { let temp; let i = 0; let r = ''; for (let val of str) { temp = val.codePointAt(0).toString(16); while ( temp.length < 4 ) temp = '0' + temp; r += '\\u' + temp; }; return r; }
//unicode編碼轉為字符串編碼
function unicodeToChar(str){ //方案一 return eval("'" + str + "'"); //方案二 return unescape(str.replace(/\u/g, "%u")); }
//js獲取字符串長度(字符真實個數) //由於es5之前都將此類四個字節組成的字符"𠮷"("𠮷".length == 2)處理成2個長度,所以使用"for of"方法可以正確遍歷字符串的長度 function getLength(str){ let length = 0; for(let val of str){ length++ } return length }
//codePointAt方法是測試一個字符由兩個字節還是由四個字節組成的最簡單方法。 function is32Bit(c) { return c.codePointAt(0) > 0xFFFF; } is32Bit("𠮷") // true is32Bit("啊") // false is32Bit("a") // false
//實際使用中,一般設計會認為中文字符如'啊','哦','額',','等理解為為兩個長度,英文字符和數字如'a','1',','等理解為為一個長度,所以此方法可以獲取他們認為的字符串長度(注意,不是字符串的真是長度,只是設計師理解的長度) function getViewLength(str){ let length = 0; for (let c of str){//注意使用for of可以正確的遍歷字符串的長度,而其他方法會將"𠮷"當成兩個長度遍歷 if(c.codePointAt(0) > 0x00FF){length = length + 2}//不管是兩個字節的字符如'啊',還是四個字節的字符'𠮷',都'當成'是屬於兩個字符長度的范圍 else{
length++
}
}
return length
}
擴展
自定義加密(這里有些限制,數值不能太大)
這里做個延伸 通過將 unicode 編碼轉換成 toString(10) 然后轉成 number 類型 在通過 ^ 異或進行轉換 這樣就進行加密了
如 ---> 加密 34 ^ 3 = 33 解密 33 ^ 3 = 34
解密思路: 將加密后的值通過 ^(異或) 運算符 進行反轉 得到 加密前的的值 然后通過將 該值轉換成 16 進制(如果本來加班前就是16進制就不用再轉了) 再通過 '\\u${十六進制}' 轉譯就可以得到原理加密的值了
const key = 313; function encryption(str) { let s = ''; str.split('').map(item => { s += handle(item); }) return s; } function decryption(str) { let s = ''; str.split('').map(item => { s += handle(item); }) return s; } function handle(str) { if (/\d/.test(str)) { return str ^ key; } else { let code = str.charCodeAt(); let newCode = code ^ key; return String.fromCharCode(newCode); } } let init = 'hello world 位運算'; let result = encryption(init); // őŜŕŕŖęŎŖŋŕŝę乴軩窮 let decodeResult = decryption(result); // hello world 位運算
摘抄於 https://www.cnblogs.com/xuanbingbingo/p/8951743.html