2017-02-20 158 views
1

給定一個輸入字段,我試圖使用正則表達式來查找文本字段中的所有URL並使它們成爲鏈接。但是,我希望保留所有信息。所以例如,我有一個輸入「http://google.com你好,這是我的內容」 - >我想分割的空白後這個正則表達式模式從另一個堆棧溢出問題(regexp = /(ftp | http | https://(\ w +:{0,1} \ w * @)?(\ S +)(:[0-9] +)?(/ | /([\ w#!:。?+ = & %@! - /]))?/),這樣我就會得到一個['http://google.com','你好,這是我的內容']。JavaScript正則表達式 - 通過正則表達式模式將字符串分割成數組

另一個前:「您好,這是我的內容http://yahoo.com測試測試http://google.com」 - >改編的[「您好,這是我的內容」,「http://yahoo.com」,「測試的測試」,「http://google.com」]

哪有這樣做?任何幫助深表感謝!

+0

'(FTP | HTTP | HTTPS):// \ S +'是足以讓URL部分 –

回答

1

首先把一切在組正則表達式到非捕獲組((?:...)),然後整個包住正則表達式組裏面,然後用它來分割這樣的字符串:

var regex = /((?:ftp|http|https):\/\/(?:\w+:{0,1}\w*@)?(?:\S+)(?::[0-9]+)?(?:\/|\/(?:[\w#!:.?+=&%@!-/]))?)/; 
var result = str.split(regex); 

例如:

var str = "hello this is my content http://yahoo.com testing testing http://google.com"; 
 

 
var regex = /((?:ftp|http|https):\/\/(?:\w+:{0,1}\w*@)?(?:\S+)(?::[0-9]+)?(?:\/|\/(?:[\w#!:.?+=&%@!-/]))?)/; 
 
var result = str.split(regex); 
 

 
console.log(result);

+0

謝謝!在使用您提供的正則表達式之後,我最終定製了它。感謝您的幫助@ibrahimmahrir – Tonyhliu

1

您的RegExp中有幾處未轉義的反斜槓。

var str = "hello this is my content http://yahoo.com testing testing http://google.com"; 
 
var captured = str.match(/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!-/]))?/g); 
 

 
var nonCaptured = []; 
 
str.split(' ').map((v,i) => captured.indexOf(v) == -1 ? nonCaptured.push(v) : null); 
 

 
console.log(nonCaptured, captured);

+0

所以這適用於我想要的url鏈接,但我也想捕獲非正則表達式內容(即「你好,這是我的內容」)到一個單獨的數組 – Tonyhliu

+0

忘記標記你:) @ kinduser – Tonyhliu

+0

@Tonyhliu完成了。 –