Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Lookbehind Assertions JavaScript Regular Expressions
Lookbehind assertions in JavaScript regular expressions allow you to match a pattern only when it's preceded by a specific pattern. They use the syntax (?<=pattern) for positive lookbehind and (?<!pattern) for negative lookbehind.
Syntax
// Positive lookbehind - match if preceded by pattern (?<=pattern) // Negative lookbehind - match if NOT preceded by pattern (?<!pattern)
Example: Extracting Prices with Positive Lookbehind
This example matches numbers that are preceded by a dollar sign:
<!DOCTYPE html>
<html>
<head>
<title>Lookbehind Assertions</title>
</head>
<body>
<div id="text">The prices are $50, $99, $121 and $150. But 25 and 75 are not prices.</div>
<button onclick="extractPrices()">Extract Prices</button>
<div id="result"></div>
<script>
function extractPrices() {
const text = document.getElementById("text").textContent;
const priceRegex = /(?<=\$)\d+/g;
const prices = text.match(priceRegex);
document.getElementById("result").innerHTML =
"Prices found: $" + prices.join(", $");
}
</script>
</body>
</html>
Output
When you click the button, it displays:
Prices found: $50, $99, $121, $150
Example: Negative Lookbehind
This example matches numbers that are NOT preceded by a dollar sign:
const text = "Items: 5 apples cost $10, 3 oranges cost $8, and 2 bananas";
const notPriceRegex = /(?<!\$)\b\d+\b/g;
const numbers = text.match(notPriceRegex);
console.log("Numbers that are not prices:", numbers);
Numbers that are not prices: [ '5', '3', '2' ]
Common Use Cases
| Pattern | Description | Example Match |
|---|---|---|
(?<=@)\w+ |
Username after @ | "user" in "@user" |
(?<=\$)\d+ |
Price after $ | "50" in "$50" |
(?<!un)\w+ed |
Words ending in "ed" not preceded by "un" | "played" but not "unplayed" |
Browser Compatibility
Lookbehind assertions are supported in modern browsers (Chrome 62+, Firefox 78+, Safari 16.4+). For older browsers, you may need alternative approaches using capturing groups.
Conclusion
Lookbehind assertions provide powerful pattern matching by checking what comes before your target. Use positive lookbehind (?<=pattern) when you need something specific before your match, and negative lookbehind (?<!pattern) when you want to exclude certain preceding patterns.
