
Question:
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?
If the style sheet is loaded to the page, you can get the <a href="https://developer.mozilla.org/en-US/docs/Web/API/StyleSheetList" rel="nofollow">StyleSheetList</a>, and pick your style sheet using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/styleSheets" rel="nofollow">document.styleSheets
</a>. After selecting the style sheet, iterate it's rules with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce?v=b" rel="nofollow">Array#reduce</a>, 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
<pre class="snippet-code-js lang-js prettyprint-override">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);
<pre class="snippet-code-css lang-css prettyprint-override">.bg {
width: 100px;
height: 100px;
}
.a {
background: url(http://lorempixel.com/200/200);
}
.b {
background: url(http://lorempixel.com/100/100);
}
<pre class="snippet-code-html lang-html prettyprint-override"><div class="bg a"></div>
<br />
<div class="bg b"></div>
Answer2:You can use .match()
, .map()
and .replace()
let res = CSSText.match(/url\(.+(?=\))/g).map(url => url.replace(/url\(/, ""));
Answer3: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 );
});
});