RegEx to extract URL from CSS background styling

前端 未结 5 1699
Happy的楠姐
Happy的楠姐 2021-02-03 11:03

I have a string in this form:

url(\"http://www.example.com/imgs/backgrounds/bg80.jpg\") repeat scroll 10% 0% transparent

This is from a CSS sty

5条回答
  •  执念已碎
    2021-02-03 11:32

    I feel like Gaby's answer is almost correct, but according to this answer, unquoted CSS URLs can include escaped characters (ex: background-image: url(http://foobar.com?\'\() is a valid way to load a background image with the url http://foobar.com?'). A more accurate expression for capturing all URLs in a stylesheet (tests here):

    /[:,\s]\s*url\s*\(\s*(?:'(\S*?)'|"(\S*?)"|((?:\\\s|\\\)|\\\"|\\\'|\S)*?))\s*\)/gi

    var urlMatchingRegex = /[:,\s]\s*url\s*\(\s*(?:'(\S*?)'|"(\S*?)"|((?:\\\s|\\\)|\\\"|\\\'|\S)*?))\s*\)/gi;
    
    myStylesheetString.replace(urlMatchingRegex, function(fullMatch, url) { 
      //Replacement handler 
    });
    

提交回复
热议问题