MarksCode MarksCode - 4 months ago 10
Javascript Question

Regex URL no numbers

I want to only execute a function if the main part of the URL is NOT followed by any numbers. For example, I want the following URL to match:

http://link.com/groups


but not

http://link.com:8001/
or
http://link.com:8000/?alert=true


I've gotten together the regex
/link.com[^0-9]+/
but it still matches the first part of the links I don't want matched so when I have the statement:

var link = document.URL;
var re = /link.com[^0-9]+/;
if (re.exec(link)){
console.log("hello");
}


"hello" still gets logged out. Is there a way to only execute the function if there are no numbers after the main part of the URL even if part of the URL matches?

Answer

Use a negative lookahead (?!...)

/link\.com(?!:\d)/

var link = "http://link.com:8000/?alert=true";
var re = /link\.com(?!:\d)/;
if (re.exec(link)) {
  console.log("hello");
} else {
  console.log("no match");  
}

Regex101 Demo

Comments