there is country code in url which i need to extract by regex and javascript.
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
^.{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]); });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.