[JavaScript] How to Extract Only URL from CSS background-image
I’ll introduce how to extract only the URL from CSS background-image using JavaScript.
background-image - CSS: カスケーディングスタイルシート | MDN
background-image: url("https://example.com/bg-image.png");
var backgroundImage = 'url("https://example.com/bg-image.png")';
var backgroundImageUrl = backgroundImage.replace(/^url\\(["']?/, '').replace(/["']?\\)$/, '');
console.log(backgroundImageUrl); // "https://example.com/background-image.png"
const backgroundImageUrls = [];
const elements = document.getElementsByClassName('target-class-name');
for (let index = 0; index < elements.length; index++) {
const element = elements[index];
const backgroundImage = (element.style && element.style.backgroundImage) || '';
const url = backgroundImage.replace(/^url\\(["']?/, '').replace(/["']?\\)$/, '');
backgroundImageUrls.push(url);
}
That’s all from the Gemba.