Related Articles

Related Articles

JavaScript String charAt()
  • Last Updated : 31 Aug, 2020

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

  • Example:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <script>
    function func() {
      
        // Original string
        var str = 'JavaScript is object oriented language';
      
        // Finding the character at given index 
        var value = str.charAt(0); 
        var value1 = str.charAt(4); 
        document.write(value); 
        document.write(value1);
    }
    func();
    </script>  

    chevron_right

    
    

  • Output:
    JS
    

str.charAT() Returns character at given index of string.

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. The range of this index is between 0 and length – 1, including the limits. 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
This function 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.

Examples for the above function are provided below:



Example 1:

var str = 'JavaScript is object oriented language';
print(str.charAt(9));

Output:

t

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

Example 2:

var str = 'JavaScript is object oriented language';
print(str.charAt(50));

Output:


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.

Codes for the above function are provided below:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// JavaScript to illustrate charAt() function
<script>
function func() {
  
    // Original string
    var str = 'JavaScript is object oriented language';
  
    // Finding the character at given index 
    var value = str.charAt(9);
    document.write(value);  
}
func();
</script>  

chevron_right


Output:

t

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
// JavaScript to illustrate charAt() function
function func() {
  
    // Original string
    var str = 'JavaScript is object oriented language';
  
    // Finding the character at given index 
    var value = str.charAt(50);
    document.write(value);    
}
func();
</script>  

chevron_right


Output:


full-stack-img




My Personal Notes arrow_drop_up
Recommended Articles
Page :