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;
});
});
一你的問題是URL不能被任何東西分隔。這會讓你的正則表達式非常複雜,因爲它現在必須瞭解URL的格式。即使你將自己限制在http :,它仍然很難。 – Arkadiy 2010-11-29 22:36:48
@Arkadiy:我無法控制什麼人輸入留言框=( – Mottie 2010-11-29 22:42:20