js charcodeat java_[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++;

}returnbytes;

}

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));

}returntemp;

}

$.toHex=function(ascii) {var temp = '';for (var i = 0; i < ascii.length; i++) {

temp+= ascii.charCodeAt(i).toString(16);

}returntemp;

}return$;

})();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值