//字符串編碼轉爲unicode編碼javascript
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編碼轉爲字符串編碼java
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 }