2010-08-17 31 views
1

我想使用javascript regexp從html代碼中選擇圖像源url。我正在使用它來簡化在其他網站中使用picasaweb圖像。我在這方面頗爲新穎,我使用http://www.regular-expressions.info/javascriptexample.html構建了一個正則表達式,在那裏它像一個魅力一樣工作,但不在我自己的腳本中。有人能指出我腳本中的錯誤嗎?使用javascript正則表達式從html中選擇圖像url

function addImage() { 
var picasaDump=prompt("Copy the picasa link"); 
if (picasaDump!=null && picasaDump!="") 
{ 
    var regMatch = new RegExp("http:\/\/\S\.[jJ][pP][eE]?[gG]"); 
    var imageLink = regMatch.exec(picasaDump); 
    if(imageLink == null) { 
     alert("Error, no images found"); 
    } else if(imageLink.length > 1) { 
     alert("Error, multiple images fount"); 
    } else { 
     further parsing... 
    } 
} 
} 

編輯:一些樣品輸入

<a href="http://picasaweb.google.com/lh/photo/NHH78Y0WLPAAzIu0lzKlUA?feat=embedwebsite"><img src="http://lh3.ggpht.com/_ADW_3zOQhj8/TGgN4bXtfMI/AAAAAAAABCA/w6M-JKzNtBk/s144/DSC_2132.jpg" /></a> 

回答

0

在這一行

var regMatch = new RegExp("http:\/\/\S\.[jJ][pP][eE]?[gG]"); 

你的字符串中的字符轉義,而不是在你的正則表達式拍攝。也\S將只匹配一個字符。它應該是

var regMatch = new RegExp("http:\\/\\/\\S+\\.[jJ][pP][eE]?[gG]"); 
+0

太感謝了,這就是我正在尋找的解決方案! – TuxM 2010-08-17 13:51:46

0

您可以嘗試

var regMatch = new RegExp("http:\/\/.+?\.jpg|jpeg","gi"); 
+0

這也將匹配一個普通鏈接,我已經添加樣本輸入演示 – TuxM 2010-08-17 13:01:13

1

這裏是另一個SO跟帖說有關適當的正則表達式這個會談:Regex to check if valid URL that ends in .jpg, .png, or .gif

不管你使用的正則表達式,一個簡單的單行測試字符串是:

({Regular_Expression}>/gi).test({String_To_Test}) 

For e.g. 
(/http:\/\/.+?\.jpg|jpeg/gi).test("http://www.google.com/image.jpg") 
+0

我並不想驗證一個圖像的URL,我只是提取它 – TuxM 2010-08-17 13:15:20

0

這將最好的實現與後視。但是,由於JavaScript不支持後臺查看,因此我們必須通過反轉字符串並使用前瞻來模仿它。

String.prototype.reverse = function() { 
    return this.split('').reverse().join(''); 
}; 

var input = '<a href="http://picasaweb.google.com/lh/photo/NHH78Y0WLPAAzIu0lzKlUA?feat=embedwebsite"><img src="http://lh3.ggpht.com/_ADW_3zOQhj8/TGgN4bXtfMI/AAAAAAAABCA/w6M-JKzNtBk/s144/DSC_2132.jpg" /></a>' 
var matches = input.reverse().match(/(gepj|gpj|gif|png)\..+?\/\/:ptth(?=\"\=crs)/g); 

這將返回一個顛倒的圖像網址的數組,所以你必須重新扭轉它們。

for (i = 0; i < matches.length; i++) 
{ 
    matches[i] = matches[i].reverse(); 
} 

如果你知道你的圖像鏈接的格式,你可以指定更多前瞻的,就像這樣:

var matches = input.reverse().match(/(gepj|gpj|gif|png)\..+?\/\/:ptth(?=\"\=crs gmi)/g); 

將匹配只有<img後面緊跟着src

向後看模仿從Steven Levithan