RegEx to extract URL from CSS background styling

前端 未结 5 1712
Happy的楠姐
Happy的楠姐 2021-02-03 11:03

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 sty

5条回答
  •  野性不改
    2021-02-03 11:45

    So here's a cleaned up version that only focuses on images & converts found images relative paths to absolute. This way you can preload easily. This code creates an array with original URL and absolute URL. You can simply loop through the result and preload the absolute URL images

    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

    Here's working JSbin http://jsbin.com/nalimaruvu/2/

提交回复
热议问题