JS RegExp Metachars

JavaScript RegExp Metacharacters

In Regular Expressions, Metacharacters are characters with a special structural or structural meaning. They are the engine of regular expressions, allowing you to define wildcards, alternatives, and more.


Essential Metacharacters

Metacharacter Description
. Matches any single character, except newline or line terminator.
| Finds any of the alternatives specified (Acts as a logical OR).
\ The escape character. Escapes special characters to treat them as literal strings.

(Note: Characters like ^, $, *, +, and ? are also metacharacters, but we will cover them in the Assertions and Quantifiers chapters!)


1. The Dot Wildcard (.)

The dot . acts as a wildcard. It will match any single character except for line breaks.

The Dot Wildcard Example

let text = "That's hot! The hat is on the mat.";

// Match 'h', followed by ANY character, followed by 't' let result = text.match(/h.t/g);

console.log(result); // ["hot", "hat"]


2. Alternation (|)

The pipe character | acts like a boolean OR. It allows your regular expression to match one pattern or another pattern.

The OR Operator Example

let text = "I have a red car, a green bike, and a blue boat.";

// Find "red", OR "green", OR "blue" let result = text.match(/red|green|blue/g);

console.log(result); // ["red", "green", "blue"]


3. Escaping Characters (\)

Because characters like ., |, ?, and * have special powers in regular expressions, what happens if you actually want to search for a literal question mark or a literal period in your text?

You must escape the character by placing a backslash \ directly in front of it.

Escaping Special Characters

let text = "Hello. How are you?";

// BAD: This searches for ANY character (wildcard) console.log(text.match(/./g));

// GOOD: The backslash escapes the dot, so it searches for a literal period let period = text.match(/./g); console.log(period); // ["."]

// Escaping a question mark let question = text.match(/?/g); console.log(question); // ["?"]


Exercise

?

If you want to create a regular expression that matches a literal dollar sign ($) in a string, how should you write it?