To match all URLs except one using regex, you can use a negative lookahead assertion in your regular expression. The negative lookahead assertion specifies a condition that must not be met for a match to occur. Here’s a general example:
Suppose you want to match all URLs except for “example.com.” You can construct a regex pattern like this:
|
1 |
^(?!.*example\.com).*$ |
Explanation:
^: Start of the string.(?!.*example\.com): Negative lookahead assertion that checks if “example.com” is not present anywhere in the string..*: Match any characters zero or more times..*$: Match until the end of the string.
Here’s how you can use this regex pattern in JavaScript:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const regex = /^(?!.*example\.com).*$/; const urls = [ "https://www.example.com", "https://www.google.com", "https://www.example.org" ]; for (const url of urls) { if (regex.test(url)) { console.log(`Matched: ${url}`); } else { console.log(`Not Matched: ${url}`); } } |
In this example, the regex pattern matches all URLs that do not contain “example.com.” You can adapt the regex and replace “example.com” with the specific URL you want to exclude.