1

I have a JS regex with a negative lookbehind assertion that works fine in Chromium-based browsers:

(?<!https?:)\/\/(.+?)(?<!https?:)\/\/gmi

I need to replace it to another for cross browser compatibility (won't work in FF or Safari).

Regex means "Find and capture all occurrence inside slashes // //, except if before // stay http: or https:".

Example:

bar //foo bar// foo - match (capture //foo bar//)
//https://stackoverflow.com/// - match (capture https://stackoverflow.com/)
https://stackoverflow.com// - not match
//foo http://stackoverflow.com - not match

Live Demo

As @BaliBalo said, my current regex contains error and work not perfectly Error Demo I need capture https://stackoverflow.com/ in //https://stackoverflow.com///

John Doe
  • 73
  • 6

1 Answers1

0

If you only want to use them in a replace, you can try the opposite. Also capture what you don't want if it's there, and if that's the case just ignore the match. This behaves slightly differently in some edge cases but is acceptable in most situations.

Your regex could for example be:

let result = input.replace(/(https?:)?\/\/((?:https?:\/\/|.)+?)\/\//g, (m, e1, val) => e1 ? m : '[match](' + val + ')');
Bali Balo
  • 3,338
  • 1
  • 18
  • 35