Regular expression to grab the background-image url

Asked

Viewed 886 times

1

I’m not very good yet of regular expression. How could I do to capture only the contents present within the snippet url() of background-image?

Example:

$elemento.css('background-image'); // "url(imagem.png)"

Or else:

$element.css('background-image'); // "url(imagem.png), url(imagem2.png)"

I need to return, by pure Javascript or jQuery, the following for the cases:

['imagem.png']
['imagem.png', 'imagem2.png']

How to make a regular expression to capture this?

6 answers

3

A way that would work with Regex (although the code is inelegant) would be:

"url(abc.png);url(xyz.png)".match(/url\((.*?)\)/g)
        .map(function(url){ 
             return url.replace(/url\(|\)/g, "") 
        });

I don’t know a way to do it with a single expression.

2

It can be done like this:

console.log(verificaBg());

function verificaBg() {
  var arrayBg = [];
  $.each($('div'), function(key, val) {
    arrayBg[key] = $(this).css('background-image').match(/\((.*?)\)/)[1].replace(/('|")/g,'');
  });
  return arrayBg;
}
#bg1 {
  background-image: url('http://images.google.com/intl/en_ALL/images/logos/images_logo_lg.gif');
  width: 276px;
  height: 110px;
}
#bg2 {
  background-image: url('http://cdn.sstatic.net/stackoverflow/img/sprites.svg?v=a7723f5f7e59');
  width: 200px;
  height: 110px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="bg1"></div>
<div id="bg2"></div>

  • And when there’s two url()? So I spoke of regular expression, because I knew it would not be a simple replace.

  • @ do you want to take all the url’s of the background-image and put in an array ? do you want to do this when loading the page ?

  • 1

    Yes, I want to return them all in an array. Mount an array with these urls. Because if you have one, take one. If you have more than one, take them too.

  • @Wallacemaxters as will be different bg’s I added two div’s and 2 bg’s different to exemplify, give a look at the return...

  • I think you misunderstood when you said "two url()attributes". See what can be done in css: background-image: url(1.png), url(2.png), url(3.png); . I want to return ['1.png', '2.png', '3.png']

  • You just want to name the image.format without her path ?

Show 1 more comment

2

Taking advantage of the example posted by Gabriel Rodrigues.

function verificaBg(id) {
  var arrayBg = [];
  var elemento = document.getElementById(id);
  var styles = window.getComputedStyle(elemento);
  var matchs = styles.getPropertyValue("background-image").match(/\((.*?)\)/);
  
  var urls = matchs.map(function (match, indice) {
    var url = match.replace(/('|")/g,'');
    return url;
  });
  
  return urls;
}

var array = verificaBg("bg1");
console.log(array);
#bg1 {
  background-image:
    url('http://images.google.com/intl/en_ALL/images/logos/images_logo_lg.gif'),
    url('http://cdn.sstatic.net/stackoverflow/img/sprites.svg?v=a7723f5f7e59');
  width: 276px;
  height: 110px;
}
<div id="bg1"></div>

  • this code is the best, however, because it appears twice the URL one within () and another separated by , without? can only take the one that is out of parenthesis?

2

It can be done like this:

var regex = /[-a-zA-Z0-9_.]*.png/g,
    results = [],
    html = $('div').css('background-image'),
    match;

while(match = regex.exec(html)) {
    results.push(match[0]);
}

console.log(results);
<div style="background-image:url(imagem1.png), url(imagem2.png), url(imagem3.png)"></div>

1

Regex

/url\(['"][^'"]+['"]\)/g

Pluguin

(function($){
    $.fn.getUrlBackground = function(){
        var url = [];
        jQuery(this).each(function(){
            url[url.length] = jQuery(this).css('background-image').match(/url\(['"][^'"]+['"]\)/g);
        })
        return url;
    }
})(jQuery);

Obs

I wouldn’t use it like that. It was just a demonstration;

1

I believe that regular expression should solve the problem:

var css = 'background-image: url(1.png), url(2.png), url(3.png),  url("3.png"),  url('3.png');'
var regex = /[^background\-image\:\s,\"\'\(\)]+[^url(.+)]+[^\"\')]/gi

see working here: http://regexr.com/3c35n

And here the example, giving the output of the array:

http://jsfiddle.net/ivanferrer/wzbmsy9u/

Or if you prefer, something simpler, based only on the output of background-image:

/([^url\(\)\,\'\"\;\s]+[A-z0-9])/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.