at method
The at method searches for
a character by its position number
in a string. In the method parameter,
we specify an integer, which can be
positive or negative (in this case,
the search is performed from the end
of the string).
Syntax
string.at(position number);
Example
Let's find out what character is
in the string with number 0:
let res = 'abcde'.at(0);
console.log(res);
The code execution result:
'a'
Example
Let's find out what character
is in the string numbered
-1:
let res = 'abcde'.at(-1);
console.log(res);
The code execution result:
'e'
Example
If the character was not found,
then undefined is returned:
let res = 'abcde'.at(10);
console.log(res);
The code execution result:
'undefined'
Example
You can use the at method in
combination with other string methods.
Let's look at an example using the
concat
method:
let str = 'word1'.at(0).concat('word2'.at(-1));
console.log(str);
The code execution result:
'w2'
See also
-
the
startsWithmethod
that checks the start of a string -
the
endsWithmethod
that checks the end of a string -
the
indexOfmethod
that searches for the first occurrence of a substring -
the
lastIndexOfmethod
that searches for the last occurrence of a substring -
the
includesmethod
that searches for a string