RegEx to extract URL from CSS background styling

前端 未结 5 1713
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:19

    A background url can have ' or " or none around the url inside the parenthesis

    Valid urls

    • url("http://www.example.com/imgs/backgrounds/bg80.jpg")
    • url('http://www.example.com/imgs/backgrounds/bg80.jpg')
    • url(http://www.example.com/imgs/backgrounds/bg80.jpg)

    So for a generic solution you could use

    var background = 'url("http://www.example.com/imgs/backgrounds/bg80.jpg") repeat scroll 10% 0% transparent',
        reg = /(?:\(['"]?)(.*?)(?:['"]?\))/,
        extracterUrl = reg.exec(background)[1];
    

提交回复
热议问题