Skip to content

Extract all URL links from CSS file

I have a asset file with CSS and that contains properties as: background-image: url(my-url.jpg) Im trying to extract all images from the url(). How can i achieve that in JS?

Answer

If the style sheet is loaded to the page, you can get the StyleSheetList, and pick your style sheet using document.styleSheets. After selecting the style sheet, iterate it’s rules with Array#reduce, extract the backgroundImage url using a regular expression, and if the result is not null (we have a url), push it into the urls array:

You can can get relevant s

const result = [...document.styleSheets[0].rules]
  .reduce((urls, { style }) => {
    var url = style.backgroundImage.match(/url("(.+)")/);
      
    url && urls.push(url[1]);
  
    return urls;
  }, []);
  
console.log(result);
.bg {
  width: 100px;
  height: 100px;
}

.a {
  background: url(http://lorempixel.com/200/200);
}

.b {
  background: url(http://lorempixel.com/100/100);
}
<div class="bg a"></div>

<br />

<div class="bg b"></div>