-2

Using Javascript RegExp, I'm trying to match URL like the following:

http://sub.domain.com/
http://sub1.domain.com/
http://sub100.domain.com/

I tried the following regex, which isn't working - not sure what I'm doing wrong ?

^http\:\/\/sub\d*\.domain\.com\/$

EDIT: fixed copy & paste typo

Update: For some reason, document.location.href doesn't match the regex - even though examples below (also on regex101.com) do work as expected. My workaround for now - I just match any subdomain.

..any help is much appreciated!

Uri Chandler
  • 341
  • 1
  • 2
  • 10

2 Answers2

1

i dont understand How you can compare a grape with a mango

here is the corrected regex :

 /^http\:\/\/subs\d*\.app\.clicktale\.com\/$/.test("http://subs14.app.clicktale.com/");

run this command in your console, right now.

you will get true , if you use search then you will get 0 because the index of your match is 0

aelor
  • 10,892
  • 3
  • 32
  • 48
  • You can make the last `\/` optional using `?` in case the input is `http://sub.domain.com` only. – Sabuj Hassan Mar 17 '14 at 11:21
  • @aelor For some reason, this doesn't seem to work for me when comparing with `document.location.href.search(regexHere)` I always get -1, unless I hardcode the digits that come after `sub` – Uri Chandler Mar 17 '14 at 13:05
  • @UJC what is the value of `document.location.href` that you are getting ? – aelor Mar 17 '14 at 13:52
  • @aelor the value is: `http://subs14.app.clicktale.com/` * When testing this string through regex101.com it works perfectly as expected. When testing through the console I get -1...ideas ? – Uri Chandler Mar 17 '14 at 14:04
  • dude in the regex mentioned you need to replace the domain with your own domain, nyways I will update the answer, this will surely work – aelor Mar 17 '14 at 14:08
0

Well the sub-domains you showed have the token "sub", but your REGEX is looking for "subs".

Also, no need to escape colons.

You don't say whether you wish to test for a match or actually capture the sub-domain. I'll assume the latter:

var match = "http://foo.bar.com".match(/https?:\/\/(([^.]+)\.)?/);
alert(match[2]); //"foo"
Mitya
  • 33,629
  • 9
  • 60
  • 107