Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx to extract URL from CSS background styling

I have a string in this form:

url("http://www.example.com/imgs/backgrounds/bg80.jpg") repeat scroll 10% 0% transparent

This is from a CSS styling for a certain element that at the moment isn't visible on the page. What I need to do is preload that background image, but to do this I need it's URL, and I'm trying to write a regular expression find it.

I know the http://www.example.com/imgs/backgrounds/ part remains constant, the only thing changing is the image name itself, which can end with either .jpg or .png.

This was one attempt:

(http:\/\/www.example.com\/imgs\/backgrounds\/)[\w\.\-]*

The problem with this being that only the http://www.example.com/imgs/backgrounds/ part was being picked up. So I tried this, but this doesn't work at all!

(http:\/\/www.example.com\/imgs\/backgrounds\/)[\w\.\-]*(.jpg|.png)

What am I doing wrong? Thank you for any help!

like image 389
Sean Bone Avatar asked Dec 31 '13 12:12

Sean Bone


1 Answers

A background url can have ' or " or none around the url inside the parenthesis

Valid urls

  • url("http://www.example.com/imgs/backgrounds/bg80.jpg")
  • url('http://www.example.com/imgs/backgrounds/bg80.jpg')
  • url(http://www.example.com/imgs/backgrounds/bg80.jpg)

So for a generic solution you could use

var background = 'url("http://www.example.com/imgs/backgrounds/bg80.jpg") repeat scroll 10% 0% transparent',
    reg = /(?:\(['"]?)(.*?)(?:['"]?\))/,
    extracterUrl = reg.exec(background)[1];
like image 196
Gabriele Petrioli Avatar answered Sep 18 '22 17:09

Gabriele Petrioli