javascript 正则表达式从 CSS 背景样式中提取 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20857404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
RegEx to extract URL from CSS background styling
提问by Sean Bone
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 styling for a certain element that at the moment isn't visible on the page. What I need to do is preload that background image, but to do this I need it's URL, and I'm trying to write a regular expression find it.
这是来自当前在页面上不可见的某个元素的 CSS 样式。我需要做的是预加载该背景图像,但要做到这一点,我需要它的 URL,并且我正在尝试编写一个正则表达式来查找它。
I know the http://www.example.com/imgs/backgrounds/
part remains constant, the only thing changing is the image name itself, which can end with either .jpg
or .png
.
我知道这http://www.example.com/imgs/backgrounds/
部分保持不变,唯一改变的是图像名称本身,可以以.jpg
或结尾.png
。
This was one attempt:
这是一次尝试:
(http:\/\/www.example.com\/imgs\/backgrounds\/)[\w\.\-]*
The problem with this being that only the http://www.example.com/imgs/backgrounds/
part was being picked up. So I tried this, but this doesn't work at all!
这样做的问题是只有http://www.example.com/imgs/backgrounds/
零件被拾取。所以我尝试了这个,但这根本不起作用!
(http:\/\/www.example.com\/imgs\/backgrounds\/)[\w\.\-]*(.jpg|.png)
What am I doing wrong? Thank you for any help!
我究竟做错了什么?感谢您的任何帮助!
回答by Gabriele Petrioli
A background url can have '
or "
or none around the url inside the parenthesis
背景 url 可以在括号内的 url 周围有'
或"
没有
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)
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];
回答by adeneo
回答by AlexZ
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):
我觉得 Gaby 的答案几乎是正确的,但根据这个答案,未加引号的 CSS URL 可以包含转义字符(例如:background-image: url(http://foobar.com?\'\()
是加载带有 url 的背景图像的有效方法http://foobar.com?')
。用于捕获样式表中所有 URL 的更准确的表达式(在这里测试):
/[:,\s]\s*url\s*\(\s*(?:'(\S*?)'|"(\S*?)"|((?:\\\s|\\\)|\\\"|\\\'|\S)*?))\s*\)/gi
/[:,\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
});
回答by Moshe Harush
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
/url(?:\([\'"\s]?)((?!data|http|\/\/)(\.\.?\/|\/))(.*?)(?:[\'"\s]?\))/g
回答by denisbetsi
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
所以这是一个清理版本,只关注图像并将找到的图像相对路径转换为绝对路径。这样您就可以轻松预加载。此代码创建一个包含原始 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);
Here's working JSbin http://jsbin.com/nalimaruvu/2/
这是工作 JSbin http://jsbin.com/nalimaruvu/2/