[JavaScript]Basic Implementation for Determining Inclusion Start and End Patterns

目次

Overview

When validating user input or filtering data, it is essential to determine if a string contains a specific keyword, starts with a certain prefix, or ends with a specific suffix. This article explains how to use three modern methods—includes(), startsWith(), and endsWith()—to perform high-performance and readable string checks without using regular expressions.

Specifications (Input/Output)

  • Input: A list of filename strings.
  • Output: Results determining if each filename meets specific naming conventions (prefixes, keywords, extensions).
  • Operation: Analyzes filenames and outputs the compliance status to the console and an HTML list.

Basic Usage

Call the method on the target string and pass the search string as an argument. All these methods return either true or false.

const text = "report_2024_draft.pdf";

// Partial match: Checks if "draft" is included
const hasDraft = text.includes("draft"); // true

// Prefix match: Checks if it starts with "report_"
const isReport = text.startsWith("report_"); // true

// Suffix match: Checks if it ends with ".pdf"
const isPdf = text.endsWith(".pdf"); // true

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>String Search Example</title>
    <style>
        body { font-family: sans-serif; padding: 20px; }
        .file-list { list-style: none; padding: 0; }
        .file-item {
            padding: 10px;
            margin-bottom: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .tag {
            font-size: 0.8em;
            padding: 2px 6px;
            border-radius: 4px;
            margin-left: 5px;
            color: white;
        }
        .tag-pdf { background-color: #e74c3c; }
        .tag-img { background-color: #3498db; }
        .tag-draft { background-color: #f39c12; }
        .tag-valid { background-color: #2ecc71; }
    </style>
</head>
<body>

    <h2>File Inspection Tool</h2>
    <ul id="fileList" class="file-list">
    </ul>

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

JavaScript

/**
 * List of filenames to inspect
 */
const files = [
    "report_project_a.pdf",
    "image_photo01.png",
    "memo_draft_v1.txt",
    "report_summary_draft.pdf",
    "unknown_file"
];

/**
 * Determines file characteristics and creates HTML elements
 * @param {string} fileName 
 * @returns {HTMLElement}
 */
const createListItem = (fileName) => {
    const li = document.createElement("li");
    li.className = "file-item";
    
    // Filename display
    const nameSpan = document.createElement("span");
    nameSpan.textContent = fileName;
    
    // Tag display container
    const tagContainer = document.createElement("div");

    // 1. startsWith: Check if it starts with "report_"
    if (fileName.startsWith("report_")) {
        addTag(tagContainer, "REPORT", "tag-valid");
    }

    // 2. endsWith: Check if it ends with ".pdf" or ".png"
    if (fileName.endsWith(".pdf")) {
        addTag(tagContainer, "PDF", "tag-pdf");
    } else if (fileName.endsWith(".png")) {
        addTag(tagContainer, "IMG", "tag-img");
    }

    // 3. includes: Check if "draft" is included
    if (fileName.includes("draft")) {
        addTag(tagContainer, "DRAFT", "tag-draft");
    }

    li.appendChild(nameSpan);
    li.appendChild(tagContainer);

    return li;
};

/**
 * General tag addition helper
 */
const addTag = (parent, text, className) => {
    const span = document.createElement("span");
    span.textContent = text;
    span.className = `tag ${className}`;
    parent.appendChild(span);
};

// Main process
const init = () => {
    const listContainer = document.getElementById("fileList");
    
    files.forEach(file => {
        const itemElement = createListItem(file);
        listContainer.appendChild(itemElement);
    });
};

document.addEventListener("DOMContentLoaded", init);

Customization Tips

  • Ignore Case Sensitivity: These methods are strictly case-sensitive (e.g., “Example.pdf” and “example.pdf” are different). If you want to ignore case, it is recommended to convert the string to lowercase using toLowerCase() before checking.JavaScript// Case-insensitive extension check if (fileName.toLowerCase().endsWith(".pdf")) { ... }
  • Specify Search Start Position: Both includes and startsWith allow you to specify a starting index as the second argument.
    • Example: str.startsWith("http", 0)

Important Notes

  • Case Sensitivity: As mentioned, "Apple".startsWith("apple") will be false. Pay close attention to this when handling user input.
  • Null / Undefined Errors: Calling these methods on null or undefined variables will cause an error. Ensure the variable is a string or use optional chaining (?.).
  • Empty String Behavior: Searching for an empty string, such as "".includes(""), always returns true. You may need to add an empty string check to prevent unintended results.

Advanced Applications

Implementing a Search Filter

By combining these with the filter array method, you can easily implement a search feature that extracts only data containing specific keywords.

const allProducts = ["Apple Watch", "MacBook Pro", "iPhone 15", "Apple Pencil"];

// Extract only products containing "Pro"
const proProducts = allProducts.filter(product => product.includes("Pro"));

console.log(proProducts); 
// Output: ["MacBook Pro"]

Conclusion

Use includes for simple existence checks, startsWith for prefix checks, and endsWith for suffix checks (like file extensions). These methods are faster than regular expressions and make the intent of your code clearer to others. When processing user input, always normalize the text to handle variations in capitalization.

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

この記事を書いた人

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

目次