0

I have a regex to grab background urls from css:

/(@import.*?)?url\(([^)]+)\)/gi

This works fine for most cases. However, css in the wild is another matter. Even though it is not valid, I need to match url('/pix/ajax/ajax-loader (2).gif'), as well as something more typical like url(/assets/[email protected]). I've tapped out my limited regex abilities and could use some help. The test cases I'm using are:

background: url('/pix/ajax/ajax-loader (2).gif')
background: url(/pix/ajax/ajax-loader (2).gif)
background: url(/assets/[email protected])
background: url('/assets/[email protected]')
background-image: url(file.gif);
background-image: url('file.gif') no-repeat;
background: #FF0000 url( "file.gif" ) no-repeat  ;
background: #FF0000 url( "file%20space.gif" ) no-repeat;

FYI i know regex is problematic and parsing with it is generally not the best solution, but in this case i'm stuck.

3 Answers 3

1

The following Regex machtes all your test cases:

 url\(.*\)

btw: regexpal is a good site to test your regex on the fly.

Sign up to request clarification or add additional context in comments.

1 Comment

To clarify, the CSS must not be minified or contain multiple url(...) occurrences on the same line for this to work. RegEx does not work particularly well with nesting but in this case (and assuming properly formatted CSS), this should be the accepted solution.
0
var regex = new RegExp(/^\s*background.*:.*url\((.+)\)/i);
console.log(regex.exec("background: url('/pix/ajax/ajax-loader (2).gif')")[1]);

HTH

Comments

0

This is very inelegant, but it should work to extract the URLs without the delimiters (i.e. without any single or double quotes):

url\((?:(?:\s*(?:'([^']+)'|"([^"]+)")\s*)|([^)]+))\)

You would extract any non-blank matches for groups $1, $2, or $3.

This works for all of your examples except this one:

background: url(/pix/ajax/ajax-loader (2).gif)

but for good reason, because that one has invalid syntax.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.