Start learning free

LESSON 611 OF 671 · PROJECTS: COMMAND-LINE TOOLS

grep in JavaScript: Substring Match with includes()

Practice Read the full explanation

Build a tiny version of the Unix grep command. Given a list of lines and a search pattern, return all lines that contain pattern as a substring (case-sensitive), joined by newline characters (\n).

Function signature:

grep(lines, pattern)

Example:

Input:
pattern = "err"
lines = ["error: foo", "warning", "another error", "ok"]

Output: "error: foo\nanother error"

When printed:
error: foo
another error

If no lines match, return the empty string "".

Note: real grep treats the pattern as a regular expression by default (grep -F matches plain text). Here the pattern is always plain text: just look for it literally, so characters such as . or * mean nothing special.


Iterate over the lines, keep the ones where line.includes(pattern) is true, then join("\n").

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

STEP 1 OF 5
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Grep V1 in JavaScript, explained

    Problem overview

    The method grep(lines, pattern) is a small version of the Unix grep command. It receives an array of strings and a search text, and returns every line that contains the text as a substring, joined into one string with newline characters ("\n"). The match is case-sensitive, and if nothing matches the result is the empty string.

    With pattern = "err" and lines = ["error: foo", "warning", "another error", "ok"], the lines "error: foo" and "another error" contain err, so the result is "error: foo\nanother error". Printed, that is two lines of text.

    The pattern is plain text, not a regular expression: characters such as . or * mean nothing special, so a search for a.b finds a literal a.b and nothing else.

    Approach: filter, then join

    Go through the lines in order, keep the ones that pass the test, and build the output from the kept lines. Collecting the survivors in an array and joining them at the end is cleaner than gluing strings together as you go, because join puts the separator only between items. There is no trailing newline to remove, and no matches means an empty array, which joins to the empty string, exactly what the task asks for.

    The test itself is String.prototype.includes. "error: foo".includes("err") is true when the text appears anywhere in the string, not only at the start, and it compares exactly, so capitals matter.

    Step by step

    1. Create result as an empty array with let. It starts empty because nothing has matched before any line is checked.
    2. Loop over the positions with for (let i = 0; i < lines.length; i++), so that lines[i] is the current line.
    3. Test the line with if (lines[i].includes(pattern)).
    4. Push the line onto result inside the if. Only lines that passed the test get there.
    5. Return result.join("\n") after the loop.

    The solution in JavaScript

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

    Details a learner might trip on:

    • includes treats its argument as plain text. That is why the lesson can promise that . and * are not special: the call ["a.b", "axb"] searched for "a.b" returns only "a.b".
    • The comparison is case-sensitive: "Error".includes("err") is false.
    • join("\n") puts the separator between items only, so a single match gives that line with no newline after it, and an empty array gives "".
    • The string "\n" is one newline character. If you print the result with console.log, it shows as separate lines.

    Complexity

    Each line is checked once, and a substring search costs time proportional to the line's length times the pattern's length in the worst case, so the whole run is bounded by the total text size times the pattern length. The result array holds up to all the lines, so the extra space is O(L) references for L lines.

    Edge cases and common mistakes

    • No match. The result is "", not null and not an array.
    • Case. "Error" does not match "err" here.
    • Empty pattern. includes("") is true for every string, so every line would be kept.
    • Returning the array instead of the joined string.
    • Building the string with += line + "\n", which leaves a trailing newline that the expected output does not have.

    Testing

    linespatternresult
    ["error: foo", "warning", "another error", "ok"]"err""error: foo\nanother error"
    ["a.b", "axb"]"a.b""a.b"
    ["ok"]"err"""
    ["Error"]"err"""
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free