-1

there is country code in url which i need to extract by regex and javascript.

so my possible url would be

http://example.com/gb/index.aspx

http://localhost:2020/gb/index.aspx

http://example:2020/gb/index.aspx

these code i tried but regex works for a specific type of url.

var url = "http://example.com/gb/index.aspx";
//Get the language code
var countrycode = /com\/([^\/]+)/.exec(url)[1];

the above code works when url look like http://example.com/gb/index.aspx but the moment url look like http://localhost:2020/gb/index.aspx or http://example:2020/gb/index.aspx then above code does not works. so tell me which regex i need to use which can extract country code from above 3 different kind of url. need some hint. thanks

Mou
  • 15,673
  • 43
  • 156
  • 275

1 Answers1

3

^.{8}[^\/]*\/([^\/]*)

  • ^ : anchor at start
  • .{8} :skip over first 8 chars (http(s)://)
  • [^\/]: match over any chars except '/'
  • \/ match the first slash after that
  • ([^\/]*) : create a new group and match any char except '/' (this is the country code)

var urls = [
  "http://example.com/gb/index.aspx",
  "http://localhost:2020/gb/index.aspx",
  "http://example:2020/gb/index.aspx"
];

var rxGetCountryCode = /^.{8}[^\/]*\/([^\/]*)/;

urls.forEach(function (str) {
  console.log(rxGetCountryCode.exec(str)[1]);
});
Useless Code
  • 12,123
  • 5
  • 35
  • 40
John
  • 1,313
  • 9
  • 21
  • 1
    I added the other URLs to your example for completeness. I also added the an item explaining the slash after `[^\/]`; OP seems to understand what you were doing, but just in case someone finds this in the future who doesn't understand RegEx as well. – Useless Code Nov 26 '17 at 12:53