[JavaScript] How to Extract Only URL from CSS background-image

Tadashi Shigeoka ·  Tue, December 17, 2019

I’ll introduce how to extract only the URL from CSS background-image using JavaScript.

JavaScript

Background: Want to Extract Only URL from background-image

background-image - CSS: カスケーディングスタイルシート | MDN

background-image: url("https://example.com/bg-image.png");

JavaScript Sample Code to Extract Only URL from background-image

[Basic] Extract URL from background-image

var backgroundImage = 'url("https://example.com/bg-image.png")';
var backgroundImageUrl = backgroundImage.replace(/^url\\(["']?/, '').replace(/["']?\\)$/, '');

console.log(backgroundImageUrl); // "https://example.com/background-image.png"

[Advanced] Extract URL from background-image of Elements with Specific Class Name

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.

Reference Information