Start learning free

LESSON 612 OF 671 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: grep v2 — Case-Insensitive Match

Practice

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