Convert character to ASCII code in JavaScript

How can I convert a character to its ASCII code using JavaScript?

For example:

get 10 from "\n".

9 thoughts on “Convert character to ASCII code in JavaScript”

  1. While the other answers are right, I prefer this way:

    function ascii (a) { return a.charCodeAt(0); }
    

    Then, to use it, simply:

    var lineBreak = ascii("\n");
    

    I am using this for a small shortcut system:

    $(window).keypress(function(event) {
      if (event.ctrlKey && event.which == ascii("s")) {
        savecontent();
        }
      // ...
      });
    

    And you can even use it inside map() or other methods:

    var ints = 'ergtrer'.split('').map(ascii);
    
    Reply
  2. If you have only one char and not a string, you can use:

    '\n'.charCodeAt();
    

    omitting the 0…

    It used to be significantly slower than 'n'.charCodeAt(0), but I’ve tested it now and I do not see any difference anymore (executed 10 billions times with and without the 0). Tested for performance only in Chrome and Firefox.

    Reply
  3. For those that want to get a sum of all the ASCII codes for a string:

    'Foobar'
      .split('')
      .map(x=>x.charCodeAt(0))
      .reduce((a,b)=>a+b);
    

    Or, ES6:

    [...'Foobar']
      .map(char => char.charCodeAt(0))
      .reduce((current, previous) => previous + current)
    
    Reply
  4. JavaScript stores strings as UTF-16 (double byte) so if you want to ignore the second byte just strip it out with a bitwise & operator on 0000000011111111 (ie 255):

    'a'.charCodeAt(0) & 255 === 97; // because 'a' = 97 0 
    'b'.charCodeAt(0) & 255 === 98; // because 'b' = 98 0 
    '✓'.charCodeAt(0) & 255 === 19; // because '✓' = 19 39
    
    Reply
  5. You can enter a character and get Ascii Code Using this Code

    For Example Enter a Character Like A
    You Get Ascii Code 65

    function myFunction(){
        var str=document.getElementById("id1");
        if (str.value=="") {
           str.focus();
           return;
        }
        var a="ASCII Code is == >  ";
    document.getElementById("demo").innerHTML =a+str.value.charCodeAt(0);
    }
    <p>Check ASCII code</p>
    
    <p>
      Enter any character:  
      <input type="text" id="id1" name="text1" maxLength="1">	</br>
    </p>
    
    <button onclick="myFunction()">Get ASCII code</button>
    
    <p id="demo" style="color:red;"></p>
    Reply
  6. To convert a String to a cumulative number:

    const stringToSum = str => [...str||"A"].reduce((a, x) => a += x.codePointAt(0) - 65, 0);
    
    console.log(stringToSum("A")); // 0
    console.log(stringToSum("Roko")); // 151

    Use case:

    Say you want to generate different background colors depending on a username:

    const stringToSum = str => [...str||"A"].reduce((a, x) => a += x.codePointAt(0), 0);
    
    const UI_userIcon = user => {
      const hue = (stringToSum(user.name) - 65) % 360; // "A" = hue: 0
      console.log(`Hue: ${hue}`);
      return `<div class="UserIcon" style="background:hsl(${hue}, 80%, 60%)" title="${user.name}">
        <span class="UserIcon-letter">${user.name[0].toUpperCase()}</span>
      </div>`;
    };
    
    [
      {name:"A"},
      {name:"Amanda"},
      {name:"amanda"},
      {name:"Anna"},
    ].forEach(user => {
      document.body.insertAdjacentHTML("beforeend", UI_userIcon(user));
    });
    .UserIcon {
      width: 4em;
      height: 4em;
      border-radius: 4em;
      display: inline-flex;
      justify-content: center;
      align-items: center;
    }
    
    .UserIcon-letter {
      font: 700 2em/0 sans-serif;
      color: #fff;
    }
    Reply
  7. To ensure full Unicode support and reversibility, consider using:

    '\n'.codePointAt(0);
    

    This will ensure that when testing characters over the UTF-16 limit, you will get their true code point value.

    e.g.

    '𐩕'.codePointAt(0); // 68181
    String.fromCodePoint(68181); // '𐩕'
    
    '𐩕'.charCodeAt(0);  // 55298
    String.fromCharCode(55298);  // '�'
    
    Reply
  8. str.charCodeAt(index)
    

    Using charCodeAt()
    The following example returns 65, the Unicode value for A.

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

    Reply

Leave a Comment