What regex to match all occurrences of css urls?

后端 未结 6 2131
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-20 14:36

i have a css file with a bunch of background image urls:

.alert-01 {
  background: url(\'img/alert-01.jpg\') center no-repeat;
}
.alert-02 {
  background: url(\'         


        
相关标签:
6条回答
  • 2021-02-20 14:39

    Use the following regex:

    /\burl\([^)]+\)/gi
    

    There's no need to use anchors (^ and $) as they would restrict the match over whole string input and hence fail. To capture the image path separately so that you can use it easily (and avoid substring) when constructing your <img> tags use:

    /\burl\('([^']+)'\)/gi
    

    This captures img/alert-xx.jpg in group one.

    0 讨论(0)
  • 2021-02-20 14:40
    /^url\((['"]?)(.*)\1\)$/
    

    with jQuery :

    var bg = $('.my_element').css('background-image'); // or pure js like element.style.backgroundImage
        bg = /^url\((['"]?)(.*)\1\)$/.exec(bg);
        bg = bg ? bg[2] : false;
    if(bg) {
    // Do something
    }
    

    Cross with Chrome / Firefox

    http://jsfiddle.net/KFWWv/

    0 讨论(0)
  • 2021-02-20 14:48

    Using a tool like Regexper we can see what your regular expression is matching:

    Regex Image

    As you can see there are a few problems with this:

    1. This assumes "url(" is at the start of the line.
    2. This assumes the content ends with "g)", whereas all of your examples end with "g')".
    3. This assumes after "g)" is the end of the line.

    What we instead need to do is match just "url(" [any character] ")". And we can do that using:

    /url\(.*?\)/ig
    

    Fixed Regex

    Note that I've removed the requirement for the URL ending in "g" in case the image type is .gif or any other non-jpg, jpeg or png.


    Edit: As Seçkin M commented below: what if we don't want any other url's; such as fonts which have .ttf or .eot? What is the easiest way to define an allowed extensions group?

    For this we can predefine what extensions we're looking for by putting our extensions within brackets, separated with |. For instance, if we wanted to match only gif, png, jpg or jpeg, we could use:

    /url\(.*?(gif|png|jpg|jpeg)\'\)/ig
    

    Amended Fix

    0 讨论(0)
  • 2021-02-20 14:52

    You were just not accounting for the closing quote

     url\(.*g\'\)
    

    and anchoring

    0 讨论(0)
  • 2021-02-20 14:57

    Try:

    /url\(.*?g'\)/ig
    

    Your mistake was including ^ and $ in the regexp, which anchors it to the beginning and end of the input string. And you forgot to allow for the quote.

    0 讨论(0)
  • 2021-02-20 15:00

    I came to this question from google. Old one, but none of the answer is discussing about data:image/* urls. Here is what I found on another google result that will only match http or relative urls.

    /url\((?!['"]?(?:data):)['"]?([^'"\)]*)['"]?\)/g
    

    I hope this would help other people coming from search engines.

    0 讨论(0)
提交回复
热议问题