RegEx to extract URL from CSS background styling

前端 未结 5 1700
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:19

    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];
    
    0 讨论(0)
  • 2021-02-03 11:31

    I just do it now and I get to this page so I think so my pattern its simply and absolutely:

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

    0 讨论(0)
  • 2021-02-03 11:32

    I feel like Gaby's answer is almost correct, but according to this answer, unquoted CSS URLs can include escaped characters (ex: background-image: url(http://foobar.com?\'\() is a valid way to load a background image with the 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 
    });
    
    0 讨论(0)
  • 2021-02-03 11:43

    Just capture anything between ( and )

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

    FIDDLE

    0 讨论(0)
  • 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<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);
    

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

    0 讨论(0)
提交回复
热议问题