Search code examples
javascriptcssbackground-image

How to get Css Background image URL text from relative URL?


I want to get text of background-image URL. Expect Output:

123
http://123.com
 (It is empty)

But Actual Output:

$('#p1').html($('#bg1').css('background-image').replace('url(','').replace(')','').replace(/\"/gi, ""));
$('#p2').html($('#bg2').css('background-image').replace('url(','').replace(')','').replace(/\"/gi, ""));
$('#p3').html($('#bg3').css('background-image').replace('url(','').replace(')','').replace(/\"/gi, ""));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="/1" id="bg1" style="background-image: url('123');"></a>
<p id="p1"></p>
<a href="/2" id="bg2" style="background-image: url('http://123.com');"></a>
<p id="p2"></p>
<a href="/3" id="bg3" style="background-image: url('');"></a>
<p id="p3"></p>

I know that this function can be implemented by manipulating strings.

Is there any other way?

I know this css is not specification, But I want to write GreaseMonkey UserScript to hack other Website.

Solved:

This style.backgroundImage saved me! Thank!

$.fn.extend({
    getBackgroundUrl: function () {
        let imgUrls = [];
        $(this).each(function (index, ele) {
            let bgUrl = ele.style.backgroundImage || 'url("")';
            bgUrl = bgUrl.match(/url\((['"])(.*?)\1\)/)[2];
            imgUrls.push(bgUrl);
        });
        return imgUrls.length === 1 ? imgUrls[0] : imgUrls;
    }
});
    
$('p').html($('a').getBackgroundUrl().join(','));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="/1" id="bg1" style="background-image: url('123');"></a>
<a href="/2" id="bg2" style="background-image: url('http://123.com');"></a>
<a href="/3" id="bg3" style="background-image: url('');"></a>
<p></p>


Solution

  • You can do that a lot easier with a single regular expression: match the url and the opening parentheses, capture the single or double quote, then capture and lazy-repeat characters until you get to the next single or double quote:

    const getUrl = str => str.match(/url\((['"])(.*?)\1\)/)[2];
    $('a').each((_, a) => console.log(getUrl(a.style.backgroundImage)));
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <a href="/1" id="bg1" style="background-image: url('123');"></a>
    <p id="p1"></p>
    <a href="/2" id="bg2" style="background-image: url('http://123.com');"></a>
    <p id="p2"></p>
    <a href="/3" id="bg3" style="background-image: url('');"></a>
    <p id="p3"></p>

    No need for a big library like jQuery just to select elements, you can do it in vanilla JS quite easily too:

    const getUrl = str => str.match(/url\((['"])(.*?)\1\)/)[2];
    document.querySelectorAll('a').forEach((a) => {
      console.log(getUrl(a.style.backgroundImage));
    });
    <a href="/1" id="bg1" style="background-image: url('123');"></a>
    <p id="p1"></p>
    <a href="/2" id="bg2" style="background-image: url('http://123.com');"></a>
    <p id="p2"></p>
    <a href="/3" id="bg3" style="background-image: url('');"></a>
    <p id="p3"></p>