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]);

Here,

  • 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.

Examples:

    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"

Code:

<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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.