[js] charAt()、charCodeAt()、fromCharCode()


 

String.prototype.charAt()

str.charAt(index)

 返回字符串中指定位置的字符。

 字符串中的字符從左向右索引,第一個字符的索引值為 0,最后一個字符(假設該字符位於字符串 stringName 中)的索引值為 stringName.length - 1。

如果指定的 index 值超出了該范圍,則返回一個空字符串。

            var anyString = "Brave new world";
            console.log("The character at index 0   is '" + anyString.charAt(0) + "'");
            console.log("The character at index 1   is '" + anyString.charAt(1) + "'");
            console.log("The character at index 2   is '" + anyString.charAt(2) + "'");
            console.log("The character at index 3   is '" + anyString.charAt(3) + "'");
            console.log("The character at index 4   is '" + anyString.charAt(4) + "'");
            console.log("The character at index 999 is '" + anyString.charAt(999) + "'");
//            The character at index 0 is 'B'
//            The character at index 1 is 'r'
//            The character at index 2 is 'a'
//            The character at index 3 is 'v'
//            The character at index 4 is 'e'
//            The character at index 999 is ''

 

String.prototype.charCodeAt()

str.charCodeAt(index)

返回指定索引處字符的 Unicode 數值(Unicode 編碼單元 > 0x10000 的除外)。

Unicode 編碼單元(code points)的范圍從 0 到 1,114,111。開頭的 128 個 Unicode 編碼單元和 ASCII 字符編碼一樣。
如果指定的 index 小於 0 或大於字符串的長度,則 charCodeAt 返回 NaN。

大於255為中文

"ABC".charCodeAt(0) // returns 65

 

            //求一個字符串的字節長度
            function GetBytes(str) {
                var len = str.length;
                var bytes = len;
                for (var i = 0; i < len; i++) {
                    //console.log(str[i],str.charCodeAt(i));
                    if (str.charCodeAt(i) > 255) bytes++;
                }
                return bytes;
            }
            console.log(GetBytes("你好,as"));

 

String.fromCharCode()

String.fromCharCode(num1, ..., numN)

String.fromCharCode() 靜態方法根據指定的 Unicode 編碼中的序號值來返回一個字符串。

        String.fromCharCode(65,66,67)
        //"ABC"

 

#字母 <-> ASCII <-> 十六進制

            var Converter = (function() {
                var $ = {};
                $.toAscii = function(hex) {
                    var temp = '';
                    for (var i = 0; i < hex.length; i = i + 2) {
                        temp += String.fromCharCode(parseInt(hex.slice(i, i + 2), 16));
                    }
                    return temp;
                }
                $.toHex = function(ascii) {
                    var temp = '';
                    for (var i = 0; i < ascii.length; i++) {
                        temp += ascii.charCodeAt(i).toString(16);
                    }
                    return temp;
                }
                return $;
            })();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM