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?
- 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
4 Answers
Reset to default 3If 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
版权声明:本文标题:javascript - Extract all URL links from CSS file - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745012630a2637642.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论