The Regex Cheat Sheet for JavaScript Developers
Tags: regex, javascript, programming, beginners
Published: 2023-12-07 05:29:38

Regex (Regular Expressions) are powerful tools for pattern matching and text manipulation. They provide a concise and flexible way to describe complex search patterns. In this cheat sheet, we'll cover essential regex concepts with practical examples for JavaScript developers.

## Anchors

Anchors are used to specify the position in the string where a match must occur.

```jsx
const startOfString = /^regex/;
const endOfString = /pattern$/;
const wordBoundary = /\bword\b/;
```

- `^`: Matches the start of the string.
- `$`: Matches the end of the string.
- `\b`: Matches a word boundary.

**Example:**
```jsx
console.log(startOfString.test('regex example')); // true
console.log(endOfString.test('example pattern')); // true
console.log(wordBoundary.test('word boundary')); // true
```

## Character Classes

Character classes define sets of characters to match.

```jsx
const digitClass = /\d/;
const notWhiteSpace = /\S/;
const hexDigit = /\x1F/;
```

- `\d`: Matches any digit.
- `\S`: Matches any non-whitespace character.
- `\x`: Matches a hexadecimal character.

**Example:**
```jsx
console.log(digitClass.test('abc123')); // true
console.log(notWhiteSpace.test('no whitespace')); // true
console.log(hexDigit.test('hex 1F')); // true
```

## Quantifiers

Quantifiers define the number of occurrences of a character or group.

```jsx
const zeroOrMore = /a*/;
const oneOrMore = /b+/;
const threeOrMore = /c{3,}/;
```

- `*`: Matches 0 or more occurrences.
- `+`: Matches 1 or more occurrences.
- `{3,}`: Matches 3 or more occurrences.

**Example:**
```jsx
console.log(zeroOrMore.test('aaa')); // true
console.log(oneOrMore.test('bb')); // true
console.log(threeOrMore.test('cccc')); // true
```

## Escape Sequences

Escape sequences are used to match special characters literally.

```jsx
const escapeChar = /\//;
const literalSequence = /\Qspecial\E/;
```

- `/`: Matches a literal '/'.
- `\Q...\E`: Matches the literal sequence between `\Q` and `\E`.

**Example:**
```jsx
console.log(escapeChar.test('a/b')); // true
console.log(literalSequence.test('special word')); // true
```

## Groups and Ranges

Groups and ranges help organize and match sets of characters.

```jsx
const anyCharacter = /./;
const aOrB = /(a|b)/;
const nonCapturingGroup = /(?:x|y)/;
const rangeABC = /[a-c]/;
const notABC = /[^a-c]/;
```

- `.`: Matches any character except newline.
- `(a|b)`: Matches 'a' or 'b'.
- `(?:x|y)`: Non-capturing group.
- `[a-c]`: Matches 'a', 'b', or 'c'.
- `[^a-c]`: Matches any character except 'a', 'b', or 'c'.

**Example:**
```jsx
console.log(anyCharacter.test('a\nb')); // true
console.log(aOrB.test('a')); // true
console.log(nonCapturingGroup.test('x')); // true
console.log(rangeABC.test('b')); // true
console.log(notABC.test('d')); // true
```

## Special Characters

Special characters represent common characters.

```jsx
const newLine = /\n/;
const tab = /\t/;
const hexChar = /\x1A/;
```

- `\n`: Matches a newline character.
- `\t`: Matches a tab character.
- `\x`: Matches a hexadecimal character.

**Example:**
```jsx
console.log(newLine.test('line\nbreak')); // true
console.log(tab.test('indented\tline')); // true
console.log(hexChar.test('\x1A')); // true
```

## Pattern Modifiers

Modifiers affect how the pattern is applied.

```jsx
const globalMatch = /pattern/g;
const caseInsensitive = /case/i;
const multiLine = /^start/m;
const singleLine = /line$/s;
const commentsWhitespace = /pattern/x;
```

- `g`: Global match.
- `i`: Case-insensitive.
- `m`: Multiple lines.
- `s`: Treats the string as a single line.
- `x`: Allows comments and whitespace in the pattern.

**Example:**
```jsx
console.log(globalMatch.exec('pattern pattern')); // ['pattern', 'pattern']
console.log(caseInsensitive.test('CaseInsensitive')); // true
console.log(multiLine.test('start\nline')); // true
console.log(singleLine.test('multi\nline')); // true
console.log(commentsWhitespace.test('pattern with spaces')); // true
```

## Assertions

Assertions define conditions for a match without consuming characters.

```jsx
const lookaheadAssertion = /foo(?=bar)/;
const negativeLookahead = /foo(?!bar)/;
const lookbehindAssertion = /(?<=foo)bar/;
const negativeLookbehind = /(?<!foo)bar/;
```

- `(?=bar)`: Lookahead assertion.
- `(?!bar)`: Negative lookahead.
- `(?<=foo)bar`: Lookbehind assertion.
- `(?<!foo)bar`: Negative lookbehind.

**Example:**
```jsx
console.log(lookaheadAssertion.test('foobar')); // true
console.log(negativeLookahead.test('foo123')); // true
console.log(lookbehindAssertion.test('foobar')); // true
console.log(negativeLookbehind.test('123bar')); // true
```

In conclusion, mastering regular expressions is a valuable skill for any JavaScript developer. This cheat sheet covers essential regex concepts and provides practical examples for better understanding. Use it as a quick reference when crafting powerful search patterns in your JavaScript projects.