- JavaScript String charAt()
- See Also:
- Syntax
- Parameters
- Return Value
- More Examples
- Related Pages
- Browser Support
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Charat function in javascript
- Синтаксис charAt()
- Параметры charAt()
- Возвращаемое значение charAt()
- Примеры
- Пример 1: Использование метода charAt() с целочисленным значением индекса
- Пример 2: charAt() с нецелочисленным значением индекса
- Пример 3: Без передачи параметра в charAt()
- Пример 4: Значение индекса вне диапазона в charAt()
- String.prototype.charAt()
- Try it
- Syntax
- Parameters
- Return value
- Description
- Examples
- Using charAt()
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- Метод charAt()
- Синтаксис
- Возвращаемое значение
- Примеры
- Комментарии
JavaScript String charAt()
The charAt() method returns the character at a specified index (position) in a string.
The index of the first character is 0, the second 1, .
See Also:
Syntax
Parameters
Return Value
Type | Description |
String | The character at the specified index. Empty string («») if the index is out of range. |
More Examples
Index out of range returns empty string:
Invalid index converts to 0:
Related Pages
Browser Support
charAt() is an ECMAScript1 (ES1) feature.
ES1 (JavaScript 1997) is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Charat function in javascript
Метод charAt() возвращает символ по указанному индексу в строке.
// объявление строки const string = "Hello World!"; // поиск символа по индексу 1 let index1 = string.charAt(1); console.log("Символ по индексу 1: " + index1); // Вывод в консоль: // Символ по индексу 1: e
Синтаксис charAt()
Синтаксис метода charAt() следующий:
Параметры charAt()
- index
- целое число от 0 до str.length — 1. Если index не может быть преобразован в целое число или не указан, используется значение по умолчанию 0.
Примечание: str.length возвращает длину заданной строки.
Возвращаемое значение charAt()
Возвращает строку, представляющую символ по указанному index .
Примеры
Пример 1: Использование метода charAt() с целочисленным значением индекса
// объявление строки const string1 = "Hello World!"; // поиск символа по индексу 8 let index8 = string1.charAt(8); console.log("Символ по индексу 8: " + index8);
В приведенной выше программе string1.charAt(8) возвращает символ заданной строки с индексом 8.
Поскольку индексация строки начинается с 0, индекс «r» равен 8. Следовательно, index8 возвращает «r» .
Пример 2: charAt() с нецелочисленным значением индекса
const string = "Hello World"; // поиск символа по индексу 6.3 let result1 = string.charAt(6.3); console.log("Символ по индексу 6.3: " + result1); // поиск символа по индексу 6.9 let result2 = string.charAt(6.9); console.log("Символ по индексу 6.9: " + result2); // поиск символа по индексу 6 let result3 = string.charAt(6); console.log("Символ по индексу 6: " + result3);
Символ по индексу 6.3: W Символ по индексу 6.9: W Символ по индексу 6: W
Здесь нецелочисленные значения индекса 6.3 и 6.9 преобразуются в ближайший целочисленный индекс 6. Таким образом, и string.charAt(6.3) , и string.charAt(6.9) возвращают «W» , как и string.charAt(6) .
Пример 3: Без передачи параметра в charAt()
let sentence = "Happy Birthday to you!"; // передача пустого параметра в charAt() let index4 = sentence.charAt(); console.log("Символ по индексу 0: " + index4);
Здесь мы не передали ни одного параметра в метод charAt() . Значение индекса по умолчанию равно 0, поэтому sentence.charAt() возвращает символ с индексом 0, который равен «H» .
Пример 4: Значение индекса вне диапазона в charAt()
let sentence = "Happy Birthday to you!"; // поиск символа по индексу 100 let result = sentence.charAt(100); console.log("Символ по индексу 100: " + result);
В приведенной выше программе мы передали 100 в качестве значения индекса. Поскольку в «Happy Birthday to you!» нет элемента со значением индекса 100, метод charAt() возвращает пустую строку.
String.prototype.charAt()
The charAt() method of String values returns a new string consisting of the single UTF-16 code unit at the given index.
charAt() always indexes the string as a sequence of UTF-16 code units, so it may return lone surrogates. To get the full Unicode code point at the given index, use String.prototype.codePointAt() and String.fromCodePoint() .
Try it
Syntax
Parameters
Zero-based index of the character to be returned. Converted to an integer — undefined is converted to 0.
Return value
A string representing the character (exactly one UTF-16 code unit) at the specified index . If index is out of the range of 0 – str.length — 1 , charAt() returns an empty string.
Description
Characters in a string are indexed from left to right. The index of the first character is 0 , and the index of the last character in a string called str is str.length — 1 .
Unicode code points range from 0 to 1114111 ( 0x10FFFF ). charAt() always returns a character whose value is less than 65536 , because the higher code points are represented by a pair of 16-bit surrogate pseudo-characters. Therefore, in order to get a full character with value greater than 65535 , it is necessary to retrieve not only charAt(i) , but also charAt(i + 1) (as if manipulating a string with two characters), or to use codePointAt(i) and String.fromCodePoint() instead. For information on Unicode, see UTF-16 characters, Unicode code points, and grapheme clusters.
charAt() is very similar to using bracket notation to access a character at the specified index. The main differences are:
- charAt() attempts to convert index to an integer, while bracket notation does not, and directly uses index as a property name.
- charAt() returns an empty string if index is out of range, while bracket notation returns undefined .
Examples
Using charAt()
The following example displays characters at different locations in the string «Brave new world» :
const anyString = "Brave new world"; console.log(`The character at index 0 is '$anyString.charAt()>'`); // No index was provided, used 0 as default console.log(`The character at index 0 is '$anyString.charAt(0)>'`); console.log(`The character at index 1 is '$anyString.charAt(1)>'`); console.log(`The character at index 2 is '$anyString.charAt(2)>'`); console.log(`The character at index 3 is '$anyString.charAt(3)>'`); console.log(`The character at index 4 is '$anyString.charAt(4)>'`); console.log(`The character at index 999 is '$anyString.charAt(999)>'`);
These lines display the following:
The character at index 0 is 'B' The character at index 0 is 'B' The character at index 1 is 'r' The character at index 2 is 'a' The character at index 3 is 'v' The character at index 4 is 'e' The character at index 999 is ''
charAt() may return lone surrogates, which are not valid Unicode characters.
const str = "𠮷𠮾"; console.log(str.charAt(0)); // "\ud842", which is not a valid Unicode character console.log(str.charAt(1)); // "\udfb7", which is not a valid Unicode character
To get the full Unicode code point at the given index, use an indexing method that splits by Unicode code points, such as String.prototype.codePointAt() and spreading strings into an array of Unicode code points.
const str = "𠮷𠮾"; console.log(String.fromCodePoint(str.codePointAt(0))); // "𠮷" console.log([. str][0]); // "𠮷"
Note: Avoid re-implementing the solutions above using charAt() . The detection of lone surrogates and their pairing is complex, and built-in APIs may be more performant as they directly use the internal representation of the string. Install a polyfill for the APIs mentioned above if necessary.
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jul 24, 2023 by MDN contributors.
Your blueprint for a better internet.
Метод charAt()
Метод charAt(индекс) возвращает символ строки с указанным индексом (позицией). Индекс символа в строке передается аргументом методу. Индексация символов в строке начинается с нуля до количества символов в строке минус 1.
Синтаксис
Возвращаемое значение
Результатом вызова этого метода является односимвольная или пустая строка.
Применение: Если значение индекса меньше нуля или больше либо равно string.length, яваскрипт вернет пустую строку.
Примеры
Символы в строке идут слева направо. Индекс первого символа равен 0, а последнего символа в строке str равен str.length — 1.
В ECMAScript 5 определен также другой способ доступа к отдельному символу – с помощью числового индекса в квадратных скобках:
Комментарии
- Приветствуются комментарии, соответствующие теме урока: вопросы, ответы, предложения.
- Одну строчку кода оборачивайте в тег
, несколько строчек кода — в теги
. ваш код.
.
- Допускаются ссылки на онлайн-песочницы (codepen, plnkr, JSBin и др.).
- Введение в JavaScript
- Подключение JavaScript
- Диалоговые окна JavaScript
- Синтаксис JavaScript
- Типы данных JavaScript
- Преобразование типов данных
- Переменные
- Операторы
- Арифметические операторы
- Операторы присваивания
- Операторы сравнения
- Логические операторы
- Побитовые операторы
- Условные операторы: (if), (?:)
- Прочие операторы
- Инструкция switch
- Циклы
- Функции
- Рекурсия
- Замыкания
- Объекты
- Свойства объектов
- Перебор свойств
- Проверка наличия свойств
- Методы call() и apply()
- Объект String
- Объект Array
- Регулярные выражения
- Задачи JavaScript