url中有国家/地区代码,我需要通过正则表达式和javascript提取。
http://example.com/gb/index.aspx
http://localhost:2020/gb/index.aspx
http://example:2020/gb/index.aspx
我试过这些代码,但正则表达式适用于特定类型的网址。
var url = "http://example.com/gb/index.aspx";
//Get the language code
var countrycode = /com\/([^\/]+)/.exec(url)[1];
当网址看起来像 http://example.com/gb/index.aspx 时,上述代码可以正常工作,但当前的网址看起来像 http://localhost:2020/gb/index.aspx 或 http://example:2020/gb/index.aspx 然后上面的代码不起作用。所以告诉我我需要使用哪个正则表达式可以从3种不同类型的URL中提取国家代码。需要一些提示。感谢
答案 0 :(得分:2)
^.{8}[^\/]*\/([^\/]*)
^
:开始时停泊.{8}
:跳过前8个字符(http(s)://)[^\/]
:匹配除“/”\/
匹配此后的第一个斜杠([^\/]*)
:创建一个新组并匹配除“/”之外的所有字符(这是国家/地区代码)
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]);
});