Get URL from background-image Property

19,903

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.

Share:
19,903
Ozzy
Author by

Ozzy

Updated on June 09, 2022

Comments

  • Ozzy
    Ozzy almost 2 years

    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?

  • Mottie
    Mottie almost 13 years
    @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...
  • Vikas Sharma
    Vikas Sharma over 8 years
    url.replace(/^url\(['"]?(.+)['"]?\)/,'$1'); will be shorter
  • Brandon Poe
    Brandon Poe over 8 years
    @HasanTayyarBESIK, regex is greedy, so you need to specify that you don't want quotes in your capture. ie: url.replace(/^url\(['"]?([^'"]+)['"]?\)/,'$1');
  • pery mimon
    pery mimon about 7 years
    That is little better: url.replace(/^url\(['"]?(.+?)['"]?\)/,'$1'); (not take the last " )