JavaScript regular expressions for line cleanup

A regular expression can identify patterns inside text, but whether it is a safe cleanup tool depends on the input format and the exact boundaries you intend to match. These examples use JavaScript syntax and connect regex behavior to common line-cleaning tasks.

Match blank or whitespace-only lines

When text has already been split into individual lines, /^\s*$/ matches a line containing only whitespace (including an empty string). To limit the test to ordinary spaces and tabs, use /^[ \t]*$/ instead.

const isBlank = line => /^\s*$/.test(line);

isBlank("");       // true
isBlank(" \t");    // true
isBlank("  beta"); // false

This answers a classification question: which lines are blank? A separate operation decides whether to remove them. TinyDevTools' Remove Empty Lines uses a trim-based check and keeps non-empty lines unchanged.

Anchors and the multiline flag

^ and $ anchor a pattern to the beginning and end of the input string. With the m flag, they also match at line boundaries within a multi-line string. For example, /^ERROR:/m finds a line that begins with ERROR:; without m, it only checks the start of the entire input.

const hasErrorLine = /^ERROR:/m;
hasErrorLine.test("INFO: ready\nERROR: unavailable"); // true

If the operation can split the text into lines first, matching each line separately often makes boundary behavior easier to reason about than combining multiline anchors and newline patterns.

Extract a simple key-value line

For a deliberately simple format where the first equals sign separates a key from a value, a capture pattern can extract both parts:

const match = /^([^=]+)=(.*)$/.exec("mode=fast");
if (match) {
  const [, key, value] = match;
  // key is "mode"; value is "fast"
}

This example does not define escaping, quoting, comments, or multiline values. If the real format supports those features, use its parser rather than stretching a regex beyond the grammar it describes.

Character classes, flags, and state

When not to use a regex

Regular expressions do not automatically understand CSV quoting, JSON structure, programming-language syntax, or log-event boundaries. For those formats, parse records and compare their fields. For exact whole-line deduplication, a set of line strings is more explicit; TinyDevTools' Remove Duplicate Lines keeps the first exact occurrence.

Test a pattern before applying a replacement

Try empty input, a final newline, LF and CRLF, tabs, Unicode whitespace, near-matches, and any characters that may be escaped by the format. Verify the full output on a copy before replacing source data. For broader normalization cautions, see Whitespace in Text and Code.

Advertisements