charAt() javascript
Javascript charAt()
function of string object is used to find character at any index or position in a string.
Characters of a string are indexed where the index of first character is 0, second is 1 and so on. Index of last character of the string is equal to length of string – 1.
charAt()
accepts a numeric integer and returns the character at that index. Note that returned value is also a string.
charAt(index)
where index is a number ranging from 0 to length of string – 1.
If the index is not in this range, an empty string is returned.
Default value of argument is 0. So, if you do not pass any value to charAt()
, it is treated as 0 and the first character is returned.
Javascript charAt() example
Below is an example program to get the character at index 2 or third character from a string. Example,
let str = 'Learning javascript'; console.log('Character at index 2 is: ' +str.charAt(2)); // with invalid index, return value will be '' console.log('String with invald index is: '+str.charAt(-2));
This prints
Character at index 2 is: a
String with invalid index is:
To show that the return value of charAt()
is a string, use typeof
operator with the returned value. Example,
let str = 'Learning javascript'; let c = str.charAt(2); console.log('charAt() returns a ' +typeof c);
Output at browser console is
charAt() returns a string
There are two ways to get first character of a string with
charAt()
.1. Supply 0 as argumet to
charAt()
.2. Supply no value to
charAt()
since 0 is default.
Both the examples are given below
let str = 'Learning javascript'; let first = str.charAt(1); console.log('First character with charAt(1) is: '+first); first = str.charAt(); console.log('First character with charAt() is: '+first);
This prints
First character with charAt(1) is: L
First character with charAt() is: L
Get last character of string
Index of last character of string = its length – 1.
Length of a string can be determined using its length
property. So, following code finds the last character of a string using charAt()
.
let str = 'Learning javascript'; let lastChar = str.charAt(str.length - 1); console.log('Last character of string is: ' + lastChar);
which prints
Last character of string is: t
If a decimal value is supplied to
charAt()
, it ignores the decimal part and only integer value is considered.Below example will prove this
let str = 'Learning javascript'; console.log('Character at position 2.4 is: '+str.charAt(2.4)); console.log('Character at position 2.5 is: '+str.charAt(2.5)); console.log('Character at position 2.7 is: '+str.charAt(2.5)); console.log('Character at position 2.9 is: '+str.charAt(2.9));
Output will always be same
Character at position 2.4 is: a
Character at position 2.5 is: a
Character at position 2.7 is: a
Character at position 2.9 is: a
Hope the article was useful.