2010-11-29 99 views
0

我需要一些幫助,我有一些正則表達式。基本上我有一個只顯示文字的留言框。我想用圖像替換具有鏈接和圖像網址的網址。我已經掌握了基礎知識,只是當我嘗試命名一個鏈接時,如果有多個鏈接,請檢查demo正則表達式用鏈接替換url

命名鏈接格式{name}:url應該成爲<a href="url">name</a>。我遇到的問題是在第5號喊話中,正則表達式不會正確地分割這兩個URL。

HTML

<ul> 
<li>Shout #1 and a link to google: http://www.google.com</li> 
<li>Shout #2 with an image: http://i201.photobucket.com/albums/aa236/Mottie1/SMRT.jpg</li> 
<li>Shout #3 with two links: http://www.google.com and http://www.yahoo.com</li> 
<li>Shout #4 with named link: {google}:http://www.google.com</li> 
<li>Shout #5 with two named links: {google}:http://www.google.com and {yahoo}:http://www.yahoo.com and {google}:http://www.google.com</li> 
</ul> 

腳本

var rex1 = /(\{(.+)\}:)?(http\:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+)/g, 
    rex2 = /(http\:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+\.(?:jpg|png|gif|jpeg|bmp))/g; 

$('ul li').each(function(i){ 
    var shout = $(this); 
    shout.html(function(i,h){ 
    var p = h.split(rex1), 
    img = h.match(rex2), 
    typ = (p[2] !== '') ? '<a href="$3">$2</a>' : '<a href="$3">link</a>'; 
    if (img !== null) { 
    shout.addClass('shoutWithImage') 
    typ = '<img src="' + img + '" alt="" />'; 
    } 
    return h.replace(rex1, typ); 
    }); 
}); 

更新:我想通了感謝布拉德幫助我的正則表達式。如果有人需要它,這裏是updated demo和代碼(現在在IE !!):

var rex1 = /(\{(.+?)\}:)?(http:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+)/g, 
rex2 = /(http:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+\.(?:jpg|png|gif|jpeg|bmp))/g; 

$('ul li').each(function(i) { 
    var shout = $(this); 
    shout.html(function(i, h) { 
    var txt, url = h.split(' '), 
    img = h.match(rex2); 
    if (img !== null) { 
     shout.addClass('shoutWithImage'); 
     $.each(img, function(i, image) { 
     h = h.replace(image, '<img src="' + image + '" alt="" />'); 
     }); 
    } else { 
     $.each(url, function(i, u) { 
     if (rex1.test(u)) { 
      txt = u.split(':')[0] || ' '; 
      if (txt.indexOf('{') >= 0) { 
      u = u.replace(txt + ':', ''); 
      txt = txt.replace(/[\{\}]/g, ''); 
      } else { 
      txt = ''; 
      } 
      url[i] = '<a href="' + u + '">' + ((txt == '') ? 'link' : txt) + '</a>'; 
     } 
     }); 
     h = url.join(' '); 
    } 
    return h; 
    }); 
}); 
+0

一你的問題是URL不能被任何東西分隔。這會讓你的正則表達式非常複雜,因爲它現在必須瞭解URL的格式。即使你將自己限制在http :,它仍然很難。 – Arkadiy 2010-11-29 22:36:48

+0

@Arkadiy:我無法控制什麼人輸入留言框=( – Mottie 2010-11-29 22:42:20

回答

2
(\{(.+?)\}:) 

您需要的?,使正則表達式成爲「ungreedy」,而不僅僅是尋找下一個支柱。

編輯

但是,如果刪除了{yahoo}:第二個鏈接變成空太(似乎填充錨標記,在短短無屬性)。這似乎是使用拆分而不是替換的受害者。我幾乎建議先做一次性尋找鏈接,然後回過頭來尋找圖像(我沒有看到任何損害直接關聯圖像,除非這不是一個理想的結果?)