问题描述
我有一个这种形式的字符串:
I have a string in this form:
url("http://www.example.com/imgs/backgrounds/bg80.jpg") repeat scroll 10% 0% transparent
此时在页面上不可见的某个元素。我需要做的是预先加载背景图片,但为了做到这一点,我需要它的URL,我想写一个正则表达式找到它。
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.
我知道 http://www.example.com/imgs/backgrounds/
部分保持不变,唯一改变的是图像名称本身,它可以以<$ c结尾$ c> .jpg 或 .png
。
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
.
/ p>
This was one attempt:
(http:\/\/www.example.com\/imgs\/backgrounds\/)[\w\.\-]*
问题是只有 http://www.example.com/imgs/backgrounds/
部分正在选取。所以我试过这个,但这根本不工作。
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\/)[\w\.\-]*(.jpg|.png)
我做错了什么?
推荐答案
只需捕获(
和)
var url = str.match(/\((.*?)\)/)[1].replace(/('|")/g,'');
var image = new Image();
image.src = url;
这篇关于RegEx从CSS背景样式中提取URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!