2017-09-11 56 views
-1

我有一個形象標籤下面,如何找到一個圖像標記的SRC與ALT在JS

var img = '<img src="http://fmp-8.cit.nih.gov/hembase/search2images/chrX.jpg" alt="image x">'; 

我想找到這個IMG的src,我寫了下面的代碼,

var rex = /<img[^>]+src="?([^"\s]+)"?[^>]*\/>/g; 
    while (m = rex.exec(text)) { 
    imageUrls.push(m[1]); 
} 

但我imageUrls在空甚至src元素在那裏。可以任何人請幫助我。謝謝。

var m, imageUrls = [], 
    rex = /<img[^>]+src="?([^"\s]+)"?[^>]*\/>/g; 
    while (m = rex.exec(text)) { 
imageUrls.push(m[1]); 
    }console.log(imageUrls+'lslsls') 
    for (var i = 0; i < imageUrls.length; i++) { 
    text = text.replace(/<img[^>]*>/, '<amp-img layout="responsive" class="ampimageheight" src="' + imageUrls[i] + '" width="200" height= "100"></amp-img>'); 
    } 
+0

這是爲[TO͇̹̺Ɲ̴ȳ̳寶NY](另一種情況下https://stackoverflow.com/questions/1732348/regex-match-open-標籤,除了xhtml自我包含標籤) – adeneo

回答

2

你應該把它解析爲HTML,然後使用它。正則表達式是不適合解析HTML

var img = '<img src="http://fmp-8.cit.nih.gov/hembase/search2images/chrX.jpg" alt="image x">'; 
 

 
var div = document.createElement('div'); 
 

 
div.innerHTML = img; 
 

 
var src = div.querySelector('img').src; 
 

 
console.log(src)

+0

嗨,adeneo,我使用節點js和更新我的代碼,你可以請嘗試我的代碼與圖像標籤。 – vak

+0

但您發佈的代碼看起來像客戶端代碼?否則,你可以使用像Cheerio這樣的東西來解析HTML。你不應該用正則表達式解析HTML,因爲它很有可能失敗。 – adeneo

相關問題