Start learning free

LESSON 16 OF 69 · PROJECTS: COMMAND-LINE TOOLS

grep -w in JavaScript: Whole-Word Match with a RegExp

Practice Read the full explanation

Build the -w flag of the Unix grep command. Given a list of lines and a search pattern (a single word made of letters, digits, and underscores), return all lines that contain pattern as a WHOLE word — i.e. the characters immediately before and after the match must NOT be word characters (letters, digits, or underscores). The match is case-sensitive.

Return the matching lines joined by newline characters (\n).

Function signature:

grepWord(lines, pattern)

Example:

Input:
pattern = "cat"
lines = ["cat sat", "concat", "the cat", "category"]

Output: "cat sat\nthe cat"

When printed:
cat sat
the cat

Notice that "concat" is rejected because cat is preceded by the word character n (con|cat), and "category" is rejected because cat is followed by the word character e.

A line may contain the pattern more than once. It is selected if at least one occurrence is a whole word: with pattern "cat", the line "concat cat" is selected because of its second cat. The lines contain only ASCII characters.

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


JavaScript's RegExp supports the \b word boundary anchor. Build the regex once outside the loop, then use regex.test(line).

let regex = new RegExp("\\b" + pattern + "\\b");
// per line: if (regex.test(line)) keep


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

STEP 1 OF 6
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Grep V4 in JavaScript, explained

    Problem overview

    The method grepWord(lines, pattern) is the -w flag of the Unix grep command. It returns the lines that contain the pattern as a whole word, joined by "\n". The pattern is a single word made of letters, digits and underscores, the match is case-sensitive, and the lines are plain ASCII. A match counts only if the characters right before and right after it are not word characters (letters, digits or underscores), or if the match touches the start or end of the line.

    With pattern = "cat" and lines = ["cat sat", "concat", "the cat", "category"], the result is "cat sat\nthe cat". "concat" is rejected because the cat inside it follows an n, and "category" because it is followed by e. A line may contain the pattern several times and is kept if at least one occurrence is a whole word: "concat cat" is kept because of its second cat. No match gives "".

    Approach: a regular expression with word boundaries

    The earlier grep versions used includes, which cannot tell cat from the middle of concat. Checking the neighbouring characters by hand is possible but fiddly, especially because the first cat in a line may be a bad match while a later one is good. A regular expression expresses the rule directly.

    In a regex, \b is a word boundary: a position between a word character and a non-word character, or between a word character and the start or end of the text. Wrapping the pattern as \bcat\b therefore means "cat, with a boundary on each side". The regex engine tries every position in the line, so a later good occurrence is found automatically.

    The pattern arrives as a string, so the regex is built once with new RegExp(...) before the loop and then tested against each line. Only the test changes from the earlier versions; the collect-and-join structure stays the same.

    Step by step

    1. Create result as an empty array for the matching lines.
    2. Build regex with new RegExp("\\b" + pattern + "\\b"). In a JavaScript string, "\\b" is a backslash followed by b, which is what the regex needs. Because the pattern contains only letters, digits and underscores, none of its characters have a special meaning in a regex, so it needs no escaping.
    3. Loop over the positions with for (let i = 0; i < lines.length; i++).
    4. Test the line with regex.test(lines[i]). It returns true when the regex matches anywhere in the text, and one whole-word match is enough to keep the line.
    5. Push lines[i] onto result inside the if.
    6. Return result.join("\n") after the loop.

    The solution in JavaScript

    class Solution {
        grepWord(lines, pattern) {
            let result = [];
            let regex = new RegExp("\\b" + pattern + "\\b");
            for (let i = 0; i < lines.length; i++) {
                if (regex.test(lines[i])) {
                    result.push(lines[i]);
                }
            }
            return result.join("\n");
        }
    }
    

    Details that matter here:

    • The doubled backslashes. In a normal string literal, "\b" is the backspace character, one character long, not a regex boundary. Writing "\\b" gives the two characters \b, which RegExp reads as a word boundary. Forgetting to double the backslash silently breaks the match.
    • What counts as a word character. For \b, letters, digits and the underscore are word characters. So cat_x does not match cat as a whole word, while cat-x does, because the hyphen is not a word character.
    • No g flag. The regex is created without flags, so test keeps no state between calls and the same object can safely check every line.
    • Case. Without the i flag the regex is case-sensitive, as the task requires: "Cat" is not a match for cat.

    Complexity

    Each line is scanned once by the regex engine. For a fixed word pattern the work is roughly proportional to the line length times the pattern length, so the total is bounded by the text size times the pattern length. Building the regex costs time proportional to the pattern, and happens once.

    Edge cases and common mistakes

    • Single backslashes in the string. "\bcat\b" builds a pattern full of backspace characters and finds nothing.
    • Prefix or suffix matches. "concat" and "category" must be rejected, which plain includes would not do.
    • Repeated pattern. "concat cat" is kept, since one occurrence is a whole word.
    • Underscore and digits. "cat_x" is rejected; "cat-x" is kept.
    • Pattern with special characters. This solution relies on the pattern holding only letters, digits and underscores. A pattern such as a.b would be read as a regex, where . matches any character.

    Testing

    linespatternresult
    ["cat sat", "concat", "the cat", "category"]"cat""cat sat\nthe cat"
    ["concat cat", "cat_x", "cat-x", "cat", "Cat"]"cat""concat cat\ncat-x\ncat"
    ["concat"]"cat"""
    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free