Saturday, September 21, 2024
Google search engine
HomeLanguagesJavascriptJavaScript String charAt() Method

JavaScript String charAt() Method

JavaScript str.charAt() returns the character at the given index of the string index holds the array element position.

Syntax:

character = str.charAt(index)

Arguments: The only argument to this function is the index in the string from where the single character is to be extracted. 

  • index: The range of this index is between 0 and length – 1. If no index is specified then the first character of the string is returned as 0 is the default index used for this function. 

Return Value: Returns a single character located at the index specified as the argument to the function. If the index is out of range, then this function returns an empty string.

Below is an example of the String charAt() Method.

Example 1: 

JavaScript




function func() {
    // Original string
    let str = 'JavaScript is object oriented language';
 
    // Finding the character at given index
    let value = str.charAt(0);
    let value1 = str.charAt(4);
    console.log(value);
    console.log(value1);
}
func();


Output:

J
S

Example 2: In this example, the function charAt() finds the character at index 9 and returns it. 

JavaScript




function func() {
 
    // Original string
    let str = 'JavaScript is object oriented language';
 
    // Finding the character at given index
    let value = str.charAt(9);
    console.log(value);
}
func();


Output:

t

Example 3: In this example, the function charAt() finds the character at index 50. Since the index is out of bounds for the given string therefore the function returns “”an empty string. 

JavaScript




function func() {
 
    // Original string
    let str = 'JavaScript is object oriented language';
 
    // Finding the character at given index
    let value = str.charAt(50);
    console.log(value);
}
func();


Output:

 ""

Example 4: In this example we are using a variable as the index

Javascript




let str = 'Geeksforneveropen!';
let index = 4;
 
console.log(str.charAt(index));


Output

s

We have a complete list of Javascript string methods, to check those please go through this Javascript String Complete reference article.

Supported Browser: 

  • Chrome
  • Edge
  • Firefox
  • Opera
  • Safari

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.

RELATED ARTICLES

Most Popular

Recent Comments