J

JavaScript Handbook

Clean • Professional

RegEx Assertions in JavaScript

2 minute

Regular Expression Assertions

In JavaScript, assertions are patterns that check for a condition in a string without consuming characters. They allow you to match a position rather than a literal character.

1. Word Boundary Assertions

Word Boundary (\\b)

Matches a position where a word character (\\w, i.e., [a-zA-Z0-9_]) is next to a non-word character (\\W) or the start/end of a string.

console.log("hello world".match(/\\bworld\\b/)); // ["world"]
console.log("helloworld".match(/\\bworld\\b/)); // null

Non-Word Boundary (\\B)

Matches a position that is not a word boundary, i.e., between two word characters or two non-word characters.

console.log("hello".match(/\\Bll\\B/)); // ["ll"]
console.log("hello world".match(/\\Bworld\\B/)); // null

2. Start and End of String/Line

Start of String/Line (^)

Matches the start of the string. With the m (multiline) flag, it matches the start of each line.

console.log(/^hello/.test("hello world")); // true
console.log(/^world/m.test("hello\\nworld")); // true

End of String/Line ($)

Matches the end of the string. With the m flag, it matches the end of each line.

console.log(/world$/.test("hello world")); // true
console.log(/hello$/m.test("hello\\nworld")); // true

3. Lookahead Assertions

Lookaheads check if a pattern follows the current position without consuming characters.

Positive Lookahead ((?=...))

Matches a pattern only if it is followed by another pattern.

console.log("123abc".match(/\\d+(?=abc)/)); // ["123"]
console.log("123xyz".match(/\\d+(?=abc)/)); // null

Negative Lookahead ((?!...))

Matches a pattern only if it is not followed by another pattern.

console.log("123xyz".match(/\\d+(?!abc)/)); // ["123"]
console.log("123abc".match(/\\d+(?!abc)/)); // null

4. Lookbehind Assertions

(Supported in modern JavaScript engines, ES2018+)

Lookbehinds check if a pattern precedes the current position without consuming characters.

Positive Lookbehind ((?<=...))

Matches a pattern only if it is preceded by another pattern.

console.log("abc123".match(/(?<=abc)\\d+/)); // ["123"]
console.log("xyz123".match(/(?<=abc)\\d+/)); // null

Negative Lookbehind ((?<!...))

Matches a pattern only if it is not preceded by another pattern.

console.log("xyz123".match(/(?<!abc)\d+/)); // ["123"]
console.log("abc123".match(/(?<!abc)\d+/)); // null

 

Article 0 of 0