1

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?

4
  • 1
    developer.mozilla.org/en/docs/Web/API/URL Commented Aug 4, 2016 at 4:04
  • Are you just worried about the port number, or are you worried about parameter names and/or values after the ? too? Commented Aug 4, 2016 at 4:05
  • I don't want any URL that has any numbers after it to get matched Commented Aug 4, 2016 at 4:07
  • Use the correct technical terms: "host name", and "port number". Anyway, your regexp is matching because : matches [^0-9]. Commented Aug 4, 2016 at 4:07

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

4 Comments

@MarksCode it is allowed to use multiple different regular expressions to solve different parts of the problem.
@4castle interestingly http://link.com/groups doesn't get matched which I thought that expression should have since there the pattern ":\d" does not occur at all after the initial link.com bit. Any idea why?
It does get matched, you just have to get rid of the other sample strings
@SamuelToh Put the demo in global mode by adding the g modifier off to the right like this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.