-2

JavaScript provides charAt and charCodeAt methods on strings.

  • What is the difference between these two methods?
  • When would one use on over the other?
sdgfsdh
  • 33,689
  • 26
  • 132
  • 245
  • [rtfm - charAt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt) and [charCodeAt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt). – Filburt Feb 26 '18 at 11:57
  • 1
    Does this answer your question? [Difference between codePointAt and charCodeAt](https://stackoverflow.com/questions/36527642/difference-between-codepointat-and-charcodeat) – Gereon Oct 31 '21 at 16:48

2 Answers2

7

From the MDN page on charAt

The String object's charAt() method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string.

From the MDN page on charCodeAt:

The charCodeAt() method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.

The UTF-16 code unit matches the Unicode code point for code points which can be represented in a single UTF-16 code unit. If the Unicode code point cannot be represented in a single UTF-16 code unit (because its value is greater than 0xFFFF) then the code unit returned will be the first part of a surrogate pair for the code point. If you want the entire code point value, use codePointAt().

  • If you need the char as a string, call charAt.

  • If, for some reason, you need the UTF char code, call charCodeAt

    (You could use it to increment the character for example.)

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Giannis Mp
  • 1,291
  • 6
  • 13
2
var a = 'ABC.................Z';
a.charCodeAt(0); // will return 65
a.charAt(0); // will return 'A'
M0nst3R
  • 5,186
  • 1
  • 23
  • 36