[英]javascript:How to extract country code from url using regex
there is country code in url which i need to extract by regex and javascript. 网址中有国家/地区代码,我需要通过正则表达式和javascript进行提取。
http://example.com/gb/index.aspx http://example.com/gb/index.aspx
http://localhost:2020/gb/index.aspx http:// localhost:2020 / gb / index.aspx
http://example:2020/gb/index.aspx http://示例:2020 / gb / index.aspx
these code i tried but regex works for a specific type of url. 我尝试过这些代码,但是正则表达式适用于特定类型的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. 上面的代码在url看起来像http://example.com/gb/index.aspx时起作用,但是当url看起来像http:// localhost:2020 / gb / index.aspx或http:// example:2020 / gb时/index.aspx,则以上代码不起作用。 so tell me which regex i need to use which can extract country code from above 3 different kind of url.
所以告诉我我需要使用哪个正则表达式可以从上面3种不同的url中提取国家代码。 need some hint.
需要一些提示。 thanks
谢谢
^.{8}[^\\/]*\\/([^\\/]*)
^
: anchor at start ^
:开始时的锚点 .{8}
:skip over first 8 chars (http(s)://) .{8}
:跳过前8个字符(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]); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.