[JavaScript]Finding Keyword Positions with indexOf and lastIndexOf

目次

Overview

When you want to check if a specific word is included in a string or find its exact position, you use the indexOf method. This method returns the position (index) where the search string first appears as a number. This article also covers lastIndexOf, which searches from the end of the string, and how to specify a starting position for your search.

Specifications (Input/Output)

  • Input: A string such as a filename or a sentence.
  • Output:
    • The position where the search character was found (an index starting from 0).
    • Returns -1 if the character is not found.

Basic Usage

You use the format string.indexOf(searchCharacter). The return value is the position starting from 0. For example, if it is the first character, it returns 0. If the searched character is not included, it always returns -1.

Full Code (HTML / JavaScript)

HTML (index.html)

A simple layout to display search results.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>String Search Demo</title>
    <script src="string-search.js" defer></script>
</head>
<body>
    <div class="container">
        <h1>Please check the Console</h1>
        <p>The results of the string search (index retrieval) are being output.</p>
    </div>
</body>
</html>

JavaScript (string-search.js)

This implementation uses a common professional scenario: analyzing a filename.

/**
 * Demonstration of string searching (indexOf / lastIndexOf)
 */
const runSearchDemo = () => {
    // Target string (assuming an image filename)
    const fileName = "image_photo_2026.jpg";

    console.log(`Target string: "${fileName}"`);
    console.log(`Character count: ${fileName.length}`); // 21 characters


    console.log('--- 1. Search from the front (indexOf) ---');
    
    // At what position does "photo" start?
    const searchWord1 = "photo";
    const index1 = fileName.indexOf(searchWord1);
    console.log(`Position of "${searchWord1}": ${index1}`); // 6


    console.log('--- 2. Searching for a non-existent character ---');
    
    // Check if the string contains "png"
    const searchWord2 = "png";
    const index2 = fileName.indexOf(searchWord2);
    // Returns -1 if not found
    console.log(`Position of "${searchWord2}": ${index2}`); // -1


    console.log('--- 3. Search from the end (lastIndexOf) ---');
    
    // Search for the underscore "_"
    // indexOf would find the first "_" (position 5)
    // lastIndexOf finds the last "_" (position 11)
    const searchWord3 = "_";
    const lastIndex = fileName.lastIndexOf(searchWord3);
    console.log(`Position of the last "${searchWord3}": ${lastIndex}`); // 11


    console.log('--- 4. Search with a specified starting position ---');
    
    // Search for "o" starting from the 8th character
    // The "o" in "photo" (position 6) is skipped
    const searchWord4 = "o";
    const startPos = 8;
    const indexWithStart = fileName.indexOf(searchWord4, startPos);
    console.log(`Position of "${searchWord4}" after character ${startPos}: ${indexWithStart}`); // 10
};

// Execute
runSearchDemo();

Customization Tips

The biggest advantage of this method is that you can specify the search start position as the second argument. This allows you to create logic to find the “second occurrence” of a character. Additionally, lastIndexOf is very helpful when you need to extract an extension (everything after the last dot) from a file path.

Important Notes

JavaScript string searches are strictly case-sensitive. For example, "Apple".indexOf("apple") will not match and will return -1. If you expect variations in capitalization from user input, you should convert everything to lowercase using the toLowerCase() method before searching.

Applications

Getting a File Extension

By combining lastIndexOf and slice, you can easily extract only the extension from a filename.

const file = "document.ver2.pdf";
// Find the position of the last dot
const dotIndex = file.lastIndexOf(".");

// If a dot is found, extract from the next character to the end
if (dotIndex !== -1) {
    const ext = file.slice(dotIndex + 1);
    console.log(`Extension: ${ext}`); // "pdf"
}

Conclusion

indexOf is useful not only for finding a position but also for checking if a string exists by seeing if the result is not -1. By properly choosing between indexOf to search from the front and lastIndexOf to search from the back or find the last separator, you can perform efficient string analysis.

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

この記事を書いた人

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

目次