Home »
        JavaScript
    
    String charAt() Method with Example in JavaScript
    
    
    
    
        JavaScrpt String charAt() Method: Here, we are going to learn about the charAt() method with Example in JavaScript.
        
            Submitted by IncludeHelp, on February 05, 2019
        
    
    
    String charAt() Method
    charAt() is a string method in JavaScript, it is used to get the character of specified index  from the string.
    Note:
    
        - If there is no specified index with the chatAt() method – it returns the first character of the string.
- If index is outof range with the chatAt() method – it returns null ("").
Syntax
            
    character = str.charAt([index]);
    
    
    Parameters
    
        - str is the main string, we are getting the character from.
- index is the position of the string, we want to get the character from. index is an optional parameter and it's default value is 0.
Sample Input/Output
    
    Input:
    str = "Hello123"
    index: 0
    Output:
    "H"
    Input:
    str = "Hello123"
    index: 5
    Output:
    "1"
    Input:
    str = "Hello123"
    index: 10
    Output:
    ""
    Input:
    str = "Hello123"
    index: No index
    Output:
    "H"
Example
<html>
<head>
<title>JavaScipt Example</title>
</head>
<body>
<script>		
	var str = "Hello123";
	document.write("char at 0 index: " + str.charAt(0) + "<br>");
	document.write("char at 1 index: " + str.charAt(1) + "<br>");
	document.write("char at 2 index: " + str.charAt(2) + "<br>");
	document.write("char at 3 index: " + str.charAt(3) + "<br>");
	document.write("char at 4 index: " + str.charAt(4) + "<br>");
	document.write("char at 5 index: " + str.charAt(5) + "<br>");
	document.write("char at 6 index: " + str.charAt(6) + "<br>");
	document.write("char at 7 index: " + str.charAt(7) + "<br>");
	
	//test with out of range index
	document.write("char at 10 index: " + str.charAt(10) + "<br>");
	document.write("char at -1 index: " + str.charAt(-1) + "<br>");
	//without specifying the index in function
	document.write("char at 0 index: " + str.charAt() + "<br>");
	
</script>
</body>
</html>
Output
char at 0 index: H
char at 1 index: e
char at 2 index: l
char at 3 index: l
char at 4 index: o
char at 5 index: 1
char at 6 index: 2
char at 7 index: 3
char at 10 index: 
char at -1 index: 
char at 0 index: H
	JavaScript String Object Methods »
	
	
    
    
    
    
    
  
    Advertisement
    
    
    
  
  
    Advertisement