简体   繁体   中英

How can I extract a URL from url(“http://www.example.com”)?

I need to get the URL of an element's background image with jQuery:

var foo = $('#id').css('background-image');

This results in something like url("http://www.example.com/image.gif") . How can I get just the "http://www.example.com/image.gif" part from that? typeof foo says it's a string, but the url() part makes me think that JavaScript and/or jQuery has a special URL type and that I should be able to get the location with foo.toString() . That doesn't work though.

You might want to consider regular expressions in this case:

var urlStr = 'url("http://www.foo.com/")';
var url = urlStr.replace(/^url\(['"]?([^'"]*)['"]?\);?$/, '$1');

This particular regex allows you to use formats like url(http://foo.bar/) or url("http://foo.bar/") , with single quotes instead of double quotes, or possibly with a semicolon at the end.

Note that different browser implementations may return the string in a different format. For instance, one browser may return double-quotes while another browser may return the value without quotes. This makes it awkward to parse, especially when you consider that quotes are valid as URL characters.

I would say the best approach is a good old check and slice() :

var imageUrlString = $('#id').css('background-image'),
    quote = imageUrlString.charAt(4),
    result;

if (quote == "'" || quote == '"')
    result = imageUrlString.slice(5, -2);
else
    result = imageUrlString.slice(4, -1);

Assuming the browser returns a valid string, this wouldn't fail. Even if an empty string were returned (ie, there is no background image), the result is an empty string.

You could split the string at each " and get the second element:

var foo = $('#id').css('background-image').split('"')[1];

Note: This doesn't work if your URL contains quotation marks.

There is no special URL type - it's a string representing a CSS url value. You can get the URL back out with a regex:

var foo = ${'#id').css('background-image');
var url = foo.match(/url\(['"](.*)['"]\)/)[1];

(that regex isn't foolproof, but it should work against whatever jQuery returns)

If it's always the same, I'd just take the substring of the URL without the prefix.

For instance, if it's always:

url("<URL>")
url("<otherURL>")

It's always the 5th index of the string to the len - 2

Not the best by all means, but probably faster than a Regex if you're not worried about other string formats.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM