[JavaScript]Extracting Characters to Build an Initial Letter Search Feature

目次

Overview

The charAt() method, which retrieves a character at a specified position within a string, plays a vital role in analyzing input values and determining specific patterns. This article explains how to use this method to implement a search UI that filters a list in real-time based on the “first character” entered by a user.

Specifications (Input/Output)

  • Input: Text entered into a search box.
  • Output: Displays only the items where the first character of the input matches the first character of the item’s name or initial.
  • Behavior:
    • Displays all items if the input is empty.
    • When there is input, it compares the first character of each and hides elements that do not match.

Basic Usage

Use the charAt(index) method. The argument specifies the index of the character you want to retrieve (an integer starting from 0).

const text = "Engineering";

// Get the character at the beginning (index 0)
console.log(text.charAt(0)); // Output: "E"

// Get the character at index 3
console.log(text.charAt(3)); // Output: "i"

// If you specify an index out of range
console.log(text.charAt(99)); // Output: "" (Empty string)

Full Code (HTML / JavaScript)

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Employee Filter</title>
    <style>
        body { font-family: sans-serif; padding: 20px; }
        .search-box { margin-bottom: 20px; padding: 8px; width: 100%; max-width: 300px; }
        .employee-list { list-style: none; padding: 0; }
        .employee-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
            display: block;
        }
        /* Class for hiding elements */
        .hidden { display: none; }
    </style>
</head>
<body>

    <h3>Employee Directory Search</h3>
    <p>Please enter the first letter of a name (e.g., "K" for Kate, Kevin)</p>
    
    <input type="text" id="searchInput" class="search-box" placeholder="Search by initial...">

    <ul id="employeeList" class="employee-list">
        <li class="employee-item" data-name="Alice" data-initial="A">Alice Johnson</li>
        <li class="employee-item" data-name="Bob" data-initial="B">Bob Smith</li>
        <li class="employee-item" data-name="Charlie" data-initial="C">Charlie Brown</li>
        <li class="employee-item" data-name="David" data-initial="D">David Wilson</li>
        <li class="employee-item" data-name="Eve" data-initial="E">Eve Davis</li>
        <li class="employee-item" data-name="Frank" data-initial="F">Frank Miller</li>
    </ul>

    <script src="app.js"></script>
</body>
</html>

JavaScript (app.js)

/**
 * Get references to the search box and list elements
 */
const searchInput = document.querySelector("#searchInput");
const employeeItems = document.querySelectorAll(".employee-item");

/**
 * Monitor input events and perform filtering
 */
searchInput.addEventListener("input", () => {
    // Get the input value and trim whitespace
    const inputValue = searchInput.value.trim();

    employeeItems.forEach((item) => {
        // If input is empty, show everything by removing the "hidden" class
        if (inputValue === "") {
            item.classList.remove("hidden");
            return;
        }

        // Get the target initial from the data attribute (normalize to uppercase)
        const targetInitial = item.dataset.initial.toUpperCase();
        
        // Get the first character of the input value (normalize to uppercase)
        const inputInitial = inputValue.charAt(0).toUpperCase();

        // Compare the initials
        if (inputInitial === targetInitial) {
            item.classList.remove("hidden");
        } else {
            item.classList.add("hidden");
        }
    });
});

Customization Tips

  • Expanding Data Attributes: While this example uses data-initial, you can use data-kana for Japanese phonetic searches and compare it with data-kana.charAt(0) to implement “A-Ka-Sa-Ta-Na” filtering.
  • Changing Comparison Logic: You can modify the logic to differentiate between cases (remove toUpperCase) or limit the search to numeric characters only.
  • Transition Animations: Instead of just toggling display: none, you can combine CSS opacity and transition to create smooth visual effects during filtering.

Important Notes

  • Out-of-Range Access: If charAt() is used with an index that does not exist (equal to or greater than the string length), it returns an empty string "". It does not return undefined, but you should ensure your logic handles empty strings appropriately.
  • Surrogate Pairs (Emojis, etc.): charAt() retrieves characters based on 16-bit units (UTF-16 code units). Therefore, emojis or certain complex characters may not be retrieved correctly as a single character, potentially returning garbled data. To handle these strictly, consider using Array.from(str)[0].

Advanced Applications

Dynamic Logic Based on Input Length

This example shows a hybrid implementation that uses “initial search” for single-character inputs and “partial match (includes)” for inputs with two or more characters.

const keyword = inputValue.toUpperCase();

if (keyword.length === 1) {
    // Initial letter search if 1 character (charAt)
    const isMatch = item.dataset.name.toUpperCase().charAt(0) === keyword;
    /* Toggle display based on isMatch */
} else {
    // Partial match search if 2 or more characters (includes)
    const isMatch = item.dataset.name.toUpperCase().includes(keyword);
    /* Toggle display based on isMatch */
}

Summary

The charAt() method is the most basic and high-performance way to retrieve a character at a specific position. It has high compatibility and clear intent compared to array index notation (str[0]), making it a solid choice for initial letter checks or analyzing fixed-format codes. However, for modern applications involving multiple languages or special characters, you should consider surrogate pair handling.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次