2016-11-18 84 views
1

我製作了一個正則表達式,用於捕獲鏈接的短URL。例如:從URL獲取協議,主機名和路徑

https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=picture%20of%20a%20potato 

我的正則表達式是:

/(https:\/\/.+?)\/.+/ 

現在這隻能捕捉:

https://www.google.com 

我想現在要做的就是捕捉的正則表達式存儲到一個變量。任何幫助或建議非常感謝。

+1

當你調用'.match()'它返回一個包含了比賽,所有的拍攝組的數組。順便說一句,在整個正則表達式中放置一個捕獲組是毫無意義的。 – Barmar

+0

https://www.abeautifulsite.net/parsing-urls-in-javascript –

+0

['/(https?:。*?\。{1,3})/ gi'不會捕獲https:// www .google.com'](https://regex101.com/r/CEntTi/2) –

回答

1

你的正則表達式不會捕獲到https://www.google.com

使用捕獲組並應用您的正則表達式與regex.exec()。然後訪問返回數組來設置你的變量:

str="https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=picture%20of%20a%20potato"; 
 
regex = new RegExp('(https?://.*?\)/'); 
 
match = regex.exec(str)[1]; 
 
console.log(match);

+0

謝謝,正是我期待的〜 – Basque0407

0

你不需要的 「G」 標誌,所以這將會是

var matchResult = someUrlString.match(/(https?:.*?\.{1,3})/i); 

然後matchResult將是一個數組(或null)。如果不是null,您的正則表達式將導致索引0和1都包含匹配的文本。

你的正則表達式,備案,火柴之類的東西

  • HTTP:FOO。
  • https:zimbabwe_is_nice ...
  • http:你好我的名字是亞當,你有沒有考慮過鋁製壁板?它可以爲您節省成千上萬的保養費用。
2

<a> DOM元素爲您提供了這種拆分hrefs!這裏是如何:

var a = document.createElement('a'); 
a.href = 'https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=picture%20of%20a%20potato'; 
console.log({ 
     protocol: a.protocol, 
     host: a.host, 
     hostname: a.hostname, 
     port: a.port, 
     pathname: a.pathname, 
     search: a.search 
}); 

回報:

{ 
    "protocol": "https:", 
    "host": "www.google.com", 
    "hostname": "www.google.com", 
    "port": "", 
    "pathname": "/webhp", 
    "search": "?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8" 
} 

更多信息請參見https://www.abeautifulsite.net/parsing-urls-in-javascript