簡體   English   中英

如何在 html 字符串中提取 class div 中的圖像源

[英]How to extract the source of images inside class div in html string

我有用於在 html 字符串中提取圖像源的正則表達式,效果很好。 output 在 urls 數組中:

var m,
urls = [],
str = '<img class="d-block mx-auto" src="http://www.website.com/wp-content/uploads/2020/05/66189-759x493.jpg" />,
rex = /<img[^>]+src="?([^"\s]+)"?\s*\alt="First slide">/g;
      while ( m = rex.exec( str ) ) {
          urls.push( m[1] );
      }
console.log(urls);  // ["http://www.website.com/wp-content/uploads/2020/05/66189-759x493.jpg",...]

但是,我希望 rex 僅獲取 class 輪播項目中的圖像來源:

str = '<div class="carousel-item"> <img class="d-block mx-auto" src="http://www.website.com/wp-content/uploads/2020/05/66189-759x493.jpg" />';

我會跳過正則表達式並使用 DOM 方法來獲取您想要的內容。

使用模板或 DomParser 和 querySelector

 var str = '<div class="carousel-item"> <img class="d-block mx-auto" src="http://www.website.com/wp-content/uploads/2020/05/66189-759x493.jpg" /></div>'; var temp = document.createElement("template"); temp.innerHTML = str console.log(Array.from(temp.content.querySelectorAll(".carousel-item img")).map(x => x.src)) var doc = new DOMParser().parseFromString(str, "text/html") console.log(Array.from(doc.querySelectorAll(".carousel-item img")).map(x => x.src))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM