javascript
  1. javascript-charat

JavaScript charAt()

Syntax

str.charAt(index)

Example

var str = "Hello World!";
console.log(str.charAt(0)); // Output: H
console.log(str.charAt(6)); // Output: W
console.log(str.charAt(11)); // Output: !

Output

The output of the above code will be:

H 
W
!


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>charAt() Method Example</title>
</head>
<body>

<!-- Display area for the output -->
<div id="output"></div>

<script>
    // Your JavaScript code
    var str = "Hello World!";

    // Using charAt() method
    var char1 = str.charAt(0);
    var char2 = str.charAt(6);
    var char3 = str.charAt(11);

    // Display the output in the HTML document
    document.getElementById('output').innerHTML = `
        <p>str.charAt(0): "${char1}"</p>
        <p>str.charAt(6): "${char2}"</p>
        <p>str.charAt(11): "${char3}"</p>
    `;
</script>

</body>
</html>
Try Playground

Explanation

The charAt() method in JavaScript is used to return the character at a specified index of a given string. The index passed to the method begins from 0 for the first character and can be up to the length of the string minus 1. If the specified index is not within the range of the string, an empty string is returned.

Use

The charAt() method is often used in string manipulation tasks such as:

  • Displaying the first letter of a name or word.
  • Checking whether a string contains a specific character or substring.

Important Points

  • The charAt() method extracts the character at a specified position in a string.
  • The returned value is a string containing the character.
  • If the specified index is not within the range of the string, an empty string is returned.
  • The index begins at 0 for the first character and can be up to the length of the string minus 1.

Summary

The charAt() method in JavaScript extracts the character at the specified index position of a given string, and returns it as a string. This method is useful in string manipulation and checking for specific characters or substrings.

Published on: