| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/String/charAt | [Back] [Original] |
Get to know MDN better
Esta pgina foi traduzida do ingls pela comunidade. Saiba mais e junte-se comunidade MDN Web Docs.
This feature is well established and works across many devices and browser versions. Its been available across browsers since julho de 2015.
O mtodo charAt() retorna o caractere especificado a partir de uma string.
str.charAt(index)
indexUm inteiro entre 0 e str.length - 1. Se nenhum ndice for definido, charAt() usar 0 como ndice.
Uma string representando o caractere no ndice especificado. Uma string vazia se o index fornecido estiver fora do intervalo de ndices da string str.
Caracteres em uma string so indexados da esquerda para a direita. O ndice do primeiro caractere 0 (zero), e o ndice do ltimo caractere em uma string declarada como stringName stringName.length - 1. Se o ndice que voc fornecer estiver fora do intervalo de ndices da string, JavaScript retornar uma string vazia.
Se nenhum ndice for passado para charAt(), 0 ser usado por padro.
O exemplo a seguir mostra caracteres em diferentes locais em uma string "Brave new world":
var anyString = "Brave new world";
console.log("A letra no ndice 0 '" + anyString.charAt(0) + "'");
console.log("A letra no ndice 1 '" + anyString.charAt(1) + "'");
console.log("A letra no ndice 2 '" + anyString.charAt(2) + "'");
console.log("A letra no ndice 3 '" + anyString.charAt(3) + "'");
console.log("A letra no ndice 4 '" + anyString.charAt(4) + "'");
console.log("A letra no ndice 99 '" + anyString.charAt(999) + "'");
As linhas acima retornam o seguinte:
A letra no ndice 0 'B'
A letra no ndice 1 'r'
A letra no ndice 2 'a'
A letra no ndice 3 'v'
A letra no ndice 4 'e'
A letra no ndice 99 ''
O seguinte cdigo fornece um meio de garantir que passar por um loop de string sempre fornea um caractere inteiro, mesmo se a string contiver caracteres que no esto no Plano Multilngue Bsico.
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 (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;
}
Em um ambiente ECMAScript 2016 que permite atribuio desestruturada, o seguinte cdigo uma alternativa mais sucinta e um pouco mais flexvel, pois faz incremento para uma varivel de incremento automaticamente (se o caractere justificar que seja um par substituto).
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 (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];
}
charAt() para suportar caracteres no-Plano-Multilnge-Bsico (PMB)Embora o exemplo anterior possa ser mais til para programas que devem suportar caracteres no BMP (uma vez que no exige que o chamador saiba onde qualquer caractere no BMP pode aparecer), no caso de desejar, na escolha de um caractere por ndice, para tratar os pares substitutos em uma string como os caracteres nicos que eles representam, pode-se usar o seguinte:
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;
}
| Specification |
|---|
| ECMAScript 2027 LanguageSpecification # sec-string.prototype.charat |
String.prototype.indexOf()String.prototype.lastIndexOf()String.prototype.charCodeAt()String.prototype.codePointAt()String.prototype.split()String.fromCodePoint()This page was last modified on 8 de nov. de 2023 by MDN contributors.
StringString.prototype.anchor()at()String.prototype.big()String.prototype.blink()String.prototype.bold()String.prototype.charAt()String.prototype.charCodeAt()String.prototype.codePointAt()String.prototype.concat()String.prototype.endsWith()String.prototype.fixed()String.prototype.fontcolor()String.prototype.fontsize()String.prototype.includes()String.prototype.indexOf()isWellFormed()String.prototype.italics()String.prototype.lastIndexOf()String.prototype.link()String.prototype.localeCompare()String.prototype.match()String.prototype.matchAll()String.prototype.normalize()String.prototype.padEnd()String.prototype.padStart()String.prototype.repeat()String.prototype.replace()String.prototype.replaceAll()String.prototype.search()String.prototype.slice()String.prototype.small()String.prototype.split()String.prototype.startsWith()String.prototype.strike()String.prototype.sub()String.prototype.substr()String.prototype.substring()String.prototype.sup()String.prototype.toLocaleLowerCase()String.prototype.toLocaleUpperCase()String.prototype.toLowerCase()String.prototype.toString()String.prototype.toUpperCase()toWellFormed()String.prototype.trim()String.prototype.trimEnd()String.prototype.trimStart()String.prototype.valueOf()String.prototype[@@iterator]()Object/FunctionObject.prototype.__defineGetter__()Object.prototype.__defineSetter__()Object.prototype.__lookupGetter__()Object.prototype.__lookupSetter__()Object.prototype.hasOwnProperty()Object.prototype.isPrototypeOf()Object.prototype.propertyIsEnumerable()Object.prototype.toLocaleString()Object.prototype.toString()Object.prototype.valueOf()Your blueprint for a better internet.
Portions of this content are 19982026 by individual mozilla.org contributors. Content available under a Creative Commons license.
| Web Proxy Viewer | New URL | Original Page |