Is their a negative lookbehind equivalent in JavaScript?

JavaScript supports negative lookbehind assertions in modern environments (ES2018+), but older browsers require workarounds using character classes and capturing groups.

Modern Negative Lookbehind (ES2018+)

ES2018 introduced native negative lookbehind syntax (?<!pattern):

let text = 'He said "hello" and she said "goodbye"';
let result = text.replace(/(?

He said 'hello' and she said "goodbye"

Legacy Browser Workaround

For older browsers, use character classes with capturing groups to simulate negative lookbehind:

let text = 'He said "hello" and she said "goodbye"';
// Pattern: (^|[^\])" means start of string OR non-backslash followed by quote
let result = text.replace(/(^|[^\])"/g, "$1'");
console.log(result);
He said 'hello' and she said "goodbye"

How the Workaround Works

The pattern (^|[^\])" breaks down as:

  • (^|[^\]) ? Captures either start of string OR any character except backslash
  • " ? Matches the quote to replace
  • $1' ? Replaces with the captured character plus single quote

Browser Compatibility Comparison

Method Browser Support Performance
Native (?<!pattern) Chrome 62+, Firefox 78+ Faster
Character class workaround All browsers Slightly slower

Complete Example

function replaceUnescapedQuotes(str) {
    // Try modern lookbehind first
    try {
        return str.replace(/(? {
    console.log(`Original: ${text}`);
    console.log(`Result:   ${replaceUnescapedQuotes(text)}`);
    console.log('---');
});
Original: Simple "quote" here
Result:   Simple 'quote' here
---
Original: Escaped "quote" here
Result:   Escaped "quote" here
---
Original: "Start quote and end"
Result:   'Start quote and end'
---

Conclusion

Modern JavaScript supports native negative lookbehind with (?<!pattern). For legacy browser support, use character class patterns like (^|[^\])" with capturing groups as a reliable workaround.

Updated on: 2026-03-15T23:18:59+05:30

122 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements