10

i am currently using this to get the url from the background-image property:

var url = $(this).find('div').css('background-image');
url = url.substr(4, url.length - 5);

This works fine however in some browser (IE6-9), instead of it being:

url(http://.com/)

its

url("http://.com/)

Is there a failsafe way that will just get the url from this property? without having to do browser detection or some other stuff?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Ozzy
  • 10,285
  • 26
  • 94
  • 138

1 Answers1

45

You could do:

url = url.replace(/^url\(["']?/, '').replace(/["']?\)$/, '');

This will remove url(' and url(" from the beginning of the string if it is present and ") resp. ') from the end.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 3
    @Ozzy: This is a good answer, but I wouldn't call it "failsafe" because if someone takes over your project and starts using multiple backgrounds... – Mottie Jun 18 '11 at 18:20
  • 1
    `url.replace(/^url\(['"]?(.+)['"]?\)/,'$1');` will be shorter – Errico Malatesta Aug 25 '15 at 07:19
  • @HasanTayyarBESIK, regex is greedy, so you need to specify that you don't want quotes in your capture. ie: `url.replace(/^url\(['"]?([^'"]+)['"]?\)/,'$1');` – Brandon Poe Dec 16 '15 at 15:49
  • 1
    That is little better: `url.replace(/^url\(['"]?(.+?)['"]?\)/,'$1');` (not take the last " ) – pery mimon Apr 18 '17 at 12:32