hi,欢迎访问本站!
当前位置: 首页Web前端正文

js字符与ascii码互相转换的方法

墨初 Web前端 611阅读

在javascript脚本代码中,可以利用 fromCharCode()方法与 charCodeAt() 方法,实现字符与ASCII码之间的相互转换。charCodeAt() 方法可以将字符转换为对应的ASCII码,fromCharCode()  方法可以将ASCII码转为对应的字符串。

js字符转ASCII码的方法

charCodeAt():此方法可以将一个指定的字符转为对应的ASCII码,

语法:

stringObject.charCodeAt(index)

例:

//73so.com
var str = "A";
console.log(str.charCodeAt());  // 65
var str = "a";
console.log(str.charCodeAt());  // 97
var str = "|";
console.log(str.charCodeAt());  // 124

js中ASCII码转字符的方法

fromCharCode():此方法可以将ASCII码转为其对应的字符

语法:

String.fromCharCode(n1, n2, ..., nX)

例1:

console.log(String.fromCharCode(65)); // A
console.log(String.fromCharCode(97)); // a
console.log(String.fromCharCode(124)); // |
console.log(String.fromCharCode(84));  // T
console.log(String.fromCharCode(1000)); // Ϩ

例2:

fromCharCode() 方法可以一次性转换多个ascii码,只需要将要转换的ascii传入方法中即可!

console.log(String.fromCharCode(55,51,115,111,46,99,111,109));
// 73so.com
声明:无特别说明,转载请标明本文来源!
相关推荐