admin管理员组

文章数量:1406436

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?

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?

Share Improve this question asked Oct 22, 2017 at 17:41 Donny van VDonny van V 9811 gold badge11 silver badges23 bronze badges 1
  • 1 Have you made any attempts? Can you show us your code? How far did you get, what went wrong? – David Thomas Commented Oct 22, 2017 at 18:03
Add a ment  | 

4 Answers 4

Reset to default 3

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./200/200);
}

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

<br />

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

You can use .match(), .map() and .replace()

let res = CSSText.match(/url\(.+(?=\))/g).map(url => url.replace(/url\(/, ""));

I've extended @guest271314's answer with jQuery ajax. You may use it.

$(document).ready(function() {
    $.get("main.css", function(cssContent){
        let res = cssContent.match(/url\(.+(?=\))/g).map(url => url.replace(/url\(/, ""));
        alert( res );       
    }); 
});

I just wrote an updated version of this that iterates of all stylesheets on the page:

let css_urls = [...document.styleSheets]
  .filter(sheet => {
    try { return sheet.cssRules }
    catch {}
  })
  .flatMap(sheet => Array.from(sheet.cssRules))
  .filter(rule => rule.style)
  .filter(rule => rule.style.backgroundImage !== '')
  .filter(rule => rule.style.backgroundImage !== 'initial')
  .filter(rule => rule.style.backgroundImage.includes("url"))
  .reduce((urls, {style}) => {
    urls.push(style.backgroundImage);
    return urls;
  }, []);
  
console.log(css_urls);

本文标签: javascriptExtract all URL links from CSS fileStack Overflow