【问题标题】:RegEx to extract URL from CSS background styling正则表达式从 CSS 背景样式中提取 URL
【发布时间】:2014-01-18 09:26:08
【问题描述】:

我有一个这样的字符串:

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

这是来自某个元素的 CSS 样式,该元素目前在页面上不可见。我需要做的是预加载该背景图片,但为此我需要它的 URL,并且我正在尝试编写一个正则表达式找到它。

我知道http://www.example.com/imgs/backgrounds/ 部分保持不变,唯一改变的是图像名称本身,它可以以.jpg.png 结尾。

这是一次尝试:

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

问题在于只有http://www.example.com/imgs/backgrounds/ 部分被拾取。所以我尝试了这个,但这根本不起作用!

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

我做错了什么? 感谢您的帮助!

【问题讨论】:

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

标签: javascript css regex


【解决方案1】:

背景网址可以有'" 或括号内的网址周围没有

有效网址

  • 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)

因此,您可以使用通用解决方案

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

【讨论】:

  • 这应该是公认的答案;它是一个单一的正则表达式,可以从所有可能的声明格式中提取 url,而不需要 .replace() 任何东西。
  • 正则表达式不应该也包含“url”这个词吗?
  • @UdoG 否,因为我们正在尝试提取实际的 URL 字符串。并且由于对于如何构造 background 属性的属性有非常具体的规则,因此括号内不能有任何其他内容(这是我们用来识别 url 的内容
  • 字符枚举中的管道字符是干什么的?那是错误的,不是吗?
  • 为什么包含“url”这个词是错误的?这显然不会影响组匹配的内容。
【解决方案2】:

只需捕获() 之间的任何内容

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

var image = new Image();
image.src = url;

FIDDLE

【讨论】:

  • 最好将" 设为"|' 并将其设为可选。(通用
  • 啊...简单多了!只是好奇——? 在做什么?
  • @GabyakaG.Petrioli - 我的正则表达式 foo 太差了,我不知道怎么办?
  • @Sean ? 表示惰性匹配。匹配尽可能少的字符
  • 我必须添加 url,比如 attr.match(/url((.*?))/)[1].replace(/('|")/g,'') 否则,有一种颜色(0,0,0,0),parens 只有 reg exp 正在接受。分享以防万一有人也处于这种困境。
【解决方案3】:

我觉得 Gaby 的回答几乎是正确的,但根据 this answer,未加引号的 CSS URL 可以包含转义字符(例如:background-image: url(http://foobar.com?\'\() 是使用 url http://foobar.com?') 加载背景图像的有效方法。更多用于捕获样式表中所有 URL 的准确表达式 (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 
});

【讨论】:

    【解决方案4】:

    所以这是一个只关注图像并将找到的图像相对路径转换为绝对路径的清理版本。这样您就可以轻松预加载。此代码创建一个包含原始 URL 和绝对 URL 的数组。您可以简单地遍历结果并预加载绝对 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 http://jsbin.com/nalimaruvu/2/

    【讨论】:

      【解决方案5】:

      我现在就这样做,然后我就到了这个页面,所以我认为我的模式是简单而绝对的:

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

      【讨论】:

        猜你喜欢
        • 2012-10-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多