js中ASCII碼和字符互相轉換的方法


十進制ASCII碼轉換成字符

  1. 使用String.fromCodePoint(num1[, ...[, numN]])方法
String.fromCharCode(65) // A
String.fromCharCode(90) // Z
String.fromCharCode(97) // a
String.fromCharCode(122) // z
  1. 也可以使用String.fromCharCode(num1[, ...[, numN]])方法
String.fromCodePoint(65) // A
String.fromCodePoint(90) // Z
String.fromCodePoint(97) // a
String.fromCodePoint(122) // z

fromCodePoint(), fromCharCode()兩個都是String的靜態方法,所以直接使用,不需要實例化。
兩者的主要區別是:
fromCharCode() 出現的早,可以處理常用的字符編碼
fromCodePoint() ES2015出現的,可以處理高位編碼。

字符轉換成十進制ASCII碼

'A'.charCodeAt() // 65
'a'.charCodeAt() // 97
'Z'.charCodeAt() // 90
'z'.charCodeAt() // 122

參考:

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint
  3. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt


免責聲明!

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



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