Start learning free

LESSON 612 OF 671 · PROJECTS: COMMAND-LINE TOOLS

grep -i in JavaScript: Case-Insensitive Match with toLowerCase()

Practice Read the full explanation

Build the -i flag of the Unix grep command. Given a list of lines and a search pattern, return all lines that contain pattern as a substring, ignoring letter case. Return the matching lines joined by newline characters (\n).

Function signature:

grepCaseInsensitive(lines, pattern)

Example:

Input:
pattern = "ERR"
lines = ["Error: 1", "ok"]

Output: "Error: 1"

When printed:
Error: 1

The matching is case-insensitive but the original line (preserving its original casing) is returned. If no lines match, return the empty string "". The lines contain only ASCII characters.


Compute pattern.toLowerCase() once. For each line, run line.toLowerCase().includes(lowerPattern). If true, push the ORIGINAL line.

The full solution:
class Solution {
    grepCaseInsensitive(lines, pattern) {
        let result = [];
        let lowerPattern = pattern.toLowerCase();
        for (let i = 0; i < lines.length; i++) {
            if (lines[i].toLowerCase().includes(lowerPattern)) {
                result.push(lines[i]);
            }
        }
        return result.join("\n");
    }
}

STEP 1 OF 6
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Grep V2 in JavaScript, explained

    Problem overview

    The method grepCaseInsensitive(lines, pattern) is the -i flag of the Unix grep command. It receives an array of lines and a search text, and returns every line that contains the text as a substring while ignoring letter case. The matching lines come back joined by "\n", and if none match the result is "". The lines are plain ASCII.

    With pattern = "ERR" and lines = ["Error: 1", "ok"], the first line matches even though its capitalisation differs, and the result is "Error: 1". The important detail is that the line is returned as it was written, capital E included, not in lowercase.

    Approach: compare lowercase copies, keep the originals

    The previous version used includes, which compares exactly. To ignore case, make both sides use the same case before comparing. Lowercase the pattern, lowercase the line being checked, and ask whether one includes the other. That gives a yes or no answer for each line, and the answer decides whether the original line is kept.

    That separation is the core idea: the lowercase copy is only a tool for the test. The value that goes into the result is lines[i], untouched. If you pushed the lowercase copy instead, the output would lose the capitals the task says to preserve.

    The pattern is the same for every line, so it is lowercased once, before the loop, and reused. Lowercasing it inside the loop would give the same answer but repeat the work for every line.

    Step by step

    1. Create result as an empty array. No line has matched yet.
    2. Create lowerPattern with pattern.toLowerCase(), once, before the loop.
    3. Loop over the positions with for (let i = 0; i < lines.length; i++).
    4. Test the line: lines[i].toLowerCase().includes(lowerPattern). Both sides are lowercase now, so "ERR" finds "Error". The line itself is not changed by this call.
    5. Push the original lines[i] onto result.
    6. Return result.join("\n") after the loop.

    The solution in JavaScript

    class Solution {
        grepCaseInsensitive(lines, pattern) {
            let result = [];
            let lowerPattern = pattern.toLowerCase();
            for (let i = 0; i < lines.length; i++) {
                if (lines[i].toLowerCase().includes(lowerPattern)) {
                    result.push(lines[i]);
                }
            }
            return result.join("\n");
        }
    }
    

    Language details:

    • Strings in JavaScript are immutable. toLowerCase() does not modify lines[i]; it returns a new string. That is exactly why the original is still there to push.
    • For ASCII text, which is all this lesson uses, lowercasing both sides is a reliable way to ignore case. Some other alphabets have case rules that do not map one letter to one letter, so case-insensitive matching of arbitrary text is harder than it looks.
    • Uppercasing both sides would work equally well for ASCII. What matters is using the same conversion on both.

    Complexity

    Each line is lowercased once (a copy proportional to its length) and then searched, so the total work is proportional to the text size times the pattern length at worst. The extra space is the result array plus one temporary lowercase copy of a line at a time.

    Edge cases and common mistakes

    • Lowercasing only one side. Converting just the line or just the pattern is not enough: "Error: 1".includes("err") is false, because the capital E is still there. Both sides must be converted.
    • Pushing the lowercase copy. The result would show "error: 1" instead of "Error: 1".
    • Several matches. Every matching line is kept, in the original order: with pattern "err", the lines ["Error: 1", "ERR", "fine"] give "Error: 1\nERR".
    • No match gives the empty string.

    Testing

    linespatternresult
    ["Error: 1", "ok"]"ERR""Error: 1"
    ["Error: 1", "ERR", "fine"]"err""Error: 1\nERR"
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free