String.prototype.charAt()

El m猫tode charAt() retorna el car脿cter especificat d'una cadena.

Sintaxi

str.charAt(posicio)

Par脿metres

posicio
Un nombre sencer entre 0 i la longitud de la cadena menys 1.

Descripci贸

Els car脿cters d'una cadena reben un nombre per la seva posici贸 d'esquerra a dreta. La posici贸 del primer car脿cter 茅s el 0 i la posici贸 de l'煤ltim car脿cter d'una cadena anomenada stringName 茅s stringName.length - 1. Si la posicio proporcionada est脿 fora del rang v脿lid JavaScript retornar脿 una cadena buida.

Exemples

Mostrar car脿cters de diferents posicions d'una cadena

L'exemple seg眉ent mostra alguns car脿cters a diferents posicions de la cadena "Brave new world":

var anyString = 'Brave new world';

console.log("El car脿cter a la posici贸 0   茅s '" + anyString.charAt(0)   + "'");
console.log("El car脿cter a la posici贸 1   茅s '" + anyString.charAt(1)   + "'");
console.log("El car脿cter a la posici贸 2   茅s '" + anyString.charAt(2)   + "'");
console.log("El car脿cter a la posici贸 3   茅s '" + anyString.charAt(3)   + "'");
console.log("El car脿cter a la posici贸 4   茅s '" + anyString.charAt(4)   + "'");
console.log("El car脿cter a la posici贸 999 茅s '" + anyString.charAt(999) + "'");

Les l铆nies anteriors mostren la sortida seg眉ent:

El car脿cter a la posici贸 0   茅s 'B'
El car脿cter a la posici贸 1   茅s 'r'
El car脿cter a la posici贸 2   茅s 'a'
El car脿cter a la posici贸 3   茅s 'v'
El car脿cter a la posici贸 4   茅s 'e'
El car脿cter a la posici贸 999 茅s ''

Obtenir car脿cters sencers

El codi seg眉ent garanteix obtenir un car脿cter sencer, fins i tot quan la cadena contingui car脿cters que no formen part del pla b脿sic multiling眉铆stic.

var str = 'A \uD87E\uDC04 Z'; // We could also use a non-BMP character directly
for (var i = 0, chr; i < str.length; i++) {
  if ((chr = getWholeChar(str, i)) === false) {
    continue;
  }
  // Adapt this line at the top of each loop, passing in the whole string and
  // the current iteration and returning a variable to represent the
  // individual character

  console.log(chr);
}

function getWholeChar(str, i) {
  var code = str.charCodeAt(i);

  if (Number.isNaN(code)) {
    return ''; // Position not found
  }
  if (code < 0xD800 || code > 0xDFFF) {
    return str.charAt(i);
  }

  // High surrogate (could change last hex to 0xDB7F to treat high private
  // surrogates as single characters)
  if (0xD800 <= code && code <= 0xDBFF) {
    if (str.length <= (i + 1)) {
      throw 'High surrogate without following low surrogate';
    }
    var next = str.charCodeAt(i + 1);
      if (0xDC00 > next || next > 0xDFFF) {
        throw 'High surrogate without following low surrogate';
      }
      return str.charAt(i) + str.charAt(i + 1);
  }
  // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
  if (i === 0) {
    throw 'Low surrogate without preceding high surrogate';
  }
  var prev = str.charCodeAt(i - 1);

  // (could change last hex to 0xDB7F to treat high private
  // surrogates as single characters)
  if (0xD800 > prev || prev > 0xDBFF) {
    throw 'Low surrogate without preceding high surrogate';
  }
  // We can pass over low surrogates now as the second component
  // in a pair which we have already processed
  return false;
}

En l'entorn de l'ECMAScript 2016, que soporta assignaci贸 desestructurada, es pot utilitzar el codi seg眉ent com a versi贸 alternativa m茅s flexibleenvironment which allows destructured assignment, the following is a more succinct and somewhat more flexible alternative in that it does incrementing for an incrementing variable automatically (if the character warrants it in being a surrogate pair).

var str = 'A\uD87E\uDC04Z'; // We could also use a non-BMP character directly
for (var i = 0, chr; i < str.length; i++) {
  [chr, i] = getWholeCharAndI(str, i);
  // Adapt this line at the top of each loop, passing in the whole string and
  // the current iteration and returning an array with the individual character
  // and 'i' value (only changed if a surrogate pair)

  console.log(chr);
}

function getWholeCharAndI(str, i) {
  var code = str.charCodeAt(i);

  if (Number.isNaN(code)) {
    return ''; // Position not found
  }
  if (code < 0xD800 || code > 0xDFFF) {
    return [str.charAt(i), i]; // Normal character, keeping 'i' the same
  }

  // High surrogate (could change last hex to 0xDB7F to treat high private
  // surrogates as single characters)
  if (0xD800 <= code && code <= 0xDBFF) {
    if (str.length <= (i + 1)) {
      throw 'High surrogate without following low surrogate';
    }
    var next = str.charCodeAt(i + 1);
      if (0xDC00 > next || next > 0xDFFF) {
        throw 'High surrogate without following low surrogate';
      }
      return [str.charAt(i) + str.charAt(i + 1), i + 1];
  }
  // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
  if (i === 0) {
    throw 'Low surrogate without preceding high surrogate';
  }
  var prev = str.charCodeAt(i - 1);

  // (could change last hex to 0xDB7F to treat high private surrogates
  // as single characters)
  if (0xD800 > prev || prev > 0xDBFF) {
    throw 'Low surrogate without preceding high surrogate';
  }
  // Return the next character instead (and increment)
  return [str.charAt(i + 1), i + 1];
}

Fixing charAt() to support non-Basic-Multilingual-Plane (BMP) characters

While the example above may be more frequently useful for those wishing to support non-BMP characters (since it does not require the caller to know where any non-BMP character might appear), in the event that one does wish, in choosing a character by index, to treat the surrogate pairs within a string as the single characters they represent, one can use the following:

function fixedCharAt(str, idx) {
  var ret = '';
  str += '';
  var end = str.length;

  var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  while ((surrogatePairs.exec(str)) != null) {
    var li = surrogatePairs.lastIndex;
    if (li - 2 < idx) {
      idx++;
    } else {
      break;
    }
  }

  if (idx >= end || idx < 0) {
    return '';
  }

  ret += str.charAt(idx);

  if (/[\uD800-\uDBFF]/.test(ret) && /[\uDC00-\uDFFF]/.test(str.charAt(idx + 1))) {
    // Go one further, since one of the "characters" is part of a surrogate pair
    ret += str.charAt(idx + 1);
  }
  return ret;
}

Specifications

Browser compatibility

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

See also