Lookahead and Lookbehind Assertions
Lookaround assertions are zero-width conditions — they check what precedes or follows a match position without consuming any characters in the result.
1. Positive Lookahead (?=...)
A positive lookahead (?=pattern) asserts that the specified pattern must follow the current position. Only matches are returned if the lookahead condition is satisfied:
// Match digits ONLY IF followed by "px"
"font-size: 16px, line-height: 24px, opacity: 0.8".match(/\d+(?=px)/g);
// ["16", "24"] — "0.8" is not matched because it is not followed by "px"2. Negative Lookahead (?!...)
A negative lookahead (?!pattern) asserts that the specified pattern must NOT follow the current position:
// Match digits NOT followed by "px"
"font-size: 16px, z-index: 100, opacity: 0.8".match(/\d+(?!px)\b/g);
// ["100"] — only the z-index value is matched3. Positive Lookbehind (?<=...)
A positive lookbehind (?<=pattern) asserts that the specified pattern must precede the current position:
// Match the amount AFTER a dollar sign
"Items: $24.99 and $10.50".match(/(?<=\$)\d+\.\d{2}/g);
// ["24.99", "10.50"] — only the numeric values are returned, without the $4. Negative Lookbehind (?<!...)
A negative lookbehind (?<!pattern) asserts that the specified pattern must NOT precede the current position:
// Match numbers NOT preceded by a dollar sign
"Items: $24.99 and 10.50".match(/(?<!\$)\d+\.\d{2}/g);
// ["10.50"] — only the value without $ is returnedPublished on Last updated: