RegEx从CSS背景样式中提取URL

时间:2013-12-31 12:28:02

标签: javascript css regex

我有一个这种形式的字符串:

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)

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

5 个答案:

答案 0 :(得分:17)

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

有效网址

  • 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];

答案 1 :(得分:9)

只需抓取()

之间的任何内容
var url = str.match(/\((.*?)\)/)[1].replace(/('|")/g,'');

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

FIDDLE

答案 2 :(得分:2)

我觉得Gaby的答案几乎是正确的,但根据this answer,未加引号的CSS网址可以包含转义字符(例如background-image: url(http://foobar.com?\'\()是使用网址加载背景图片的有效方式{{} 1}}。用于捕获样式表中所有URL的更准确的表达式(tests here):

http://foobar.com?')

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

答案 3 :(得分:0)

所以这是一个只关注图像和清晰度的清理版本。将找到的图像转换为绝对的相对路径这样你就可以轻松预加载。此代码创建一个包含原始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/

答案 4 :(得分:0)

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

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