RegEx for extracting URLs from CSS styles

I have a line in this form:

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

This is from the CSS style for a specific element that is not currently displayed on the page. I need to preload this background image, but for this I need a url and I'm trying to write its regular expression.

I know that part of http://www.example.com/imgs/backgrounds/ remains constant, the only thing that changes 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 is that only part of http://www.example.com/imgs/backgrounds/ selected. So I tried this, but it does not work at all!

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

What am I doing wrong? Thanks for any help!

+7
javascript css regex
source share
5 answers

Just clear something between ( and )

 var url = str.match(/\((.*?)\)/)[1].replace(/('|")/g,''); var image = new Image(); image.src = url; 

Fiddle

+7
source share

The 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 general solution, you can use

 var background = 'url("http://www.example.com/imgs/backgrounds/bg80.jpg") repeat scroll 10% 0% transparent', reg = /(?:\(['"]?)(.*?)(?:['"]?\))/, extracterUrl = reg.exec(background)[1]; 
+17
source share

I feel that Gaby's answer is almost right, but according to this answer, URLs without quotes may include escaped characters (for example: background-image: url(http://foobar.com?\'\() - a valid way to download background image with url http://foobar.com?') . A more accurate expression for capturing all URLs in a stylesheet ( tests here ):

/[:,\s]\s*url\s*\(\s*(?:'(\S*?)'|"(\S*?)"|((?:\\\s|\\\)|\\\"|\\\'|\S)*?))\s*\)/gi

 var urlMatchingRegex = /[:,\s]\s*url\s*\(\s*(?:'(\S*?)'|"(\S*?)"|((?:\\\s|\\\)|\\\"|\\\'|\S)*?))\s*\)/gi; myStylesheetString.replace(urlMatchingRegex, function(fullMatch, url) { //Replacement handler }); 
+1
source share

So, here is a cleaned version that focuses only on images and converts the found images of relative paths to absolute ones. This way you can easily load the preload. This code creates an array with the source URL and absolute URL. You can simply view the result and preload the images with an absolute URL.

 var myString = " \ background: url(../images/magnifier-ico.png) no-repeat left center; \ background: url(../../images/globe-ico.png) no-repeat; \ background: url(../images/magnifier-ico.png) no-repeat left center; \ "; var myRegexp = /(?:\(['|"]?)(.*?\.(png|jpg|gif|jpeg|tiff){1})(?:['|"]?\))/gi; // Set location of CSS file being read var cssFile = "/css/mobile/style.css"; // Figure out depth of the css file in relation to root var cssPath = cssFile.split("/").filter(function(item){return item.length>0;}); var depth = (cssPath.length); // Array to store found images var images = []; // Start search var match = myRegexp.exec(myString); while (match) { // get image var foundImage = match[1]; // Look for next one match = myRegexp.exec(myString); // Convert relative path to absolute var relativeDepth = 0; var pathRegexp = /\.\.\//gi; var pathMatch = pathRegexp.exec(foundImage); while(pathMatch){ relativeDepth++; pathMatch = pathRegexp.exec(foundImage); } // Strip the relativity var pathlessImage = foundImage.split("../").join(""); // Now to the final conversion var absolute = ""; for(var i=0;i<depth-relativeDepth-1;i++) // Reconstruct it all back absolute += "/" + cssPath[i]; // Now add image name absolute += "/" + pathlessImage; // Store final cleaned up product images.push({original:foundImage,absolute:absolute}); } console.log(images); 

JSbin works here http://jsbin.com/nalimaruvu/2/

0
source share

I just do it now and I get to this page, so I believe that my template is simple and absolute:

/url(?:\([\'"\s]?)((?!data|http|\/\/)(\.\.?\/|\/))(.*?)(?:[\'"\s]?\))/g

0
source share

All Articles