Reputation: 17381
url(image1.png), url('image2.png'), url("image3.png")
Note the '
and "
delimiters. It would be nice to handle them as well, but I'm happy if the first form is captured.
var results = 'image1.png', 'image2.png', 'image3.png';
I would like to use regular expressions in javascript to parse a string that is used as the CSS property of an element with multiple backgrounds. The aim is to get the url of the images that are put in the background of the element using CSS.
See more: http://www.css3.info/preview/multiple-backgrounds/
http://jsfiddle.net/fcx9x59r/1/
Upvotes: 0
Views: 73
Reputation: 67968
/url\(([^"']+?)\)|'([^'"]+?)'\)|"([^'"]+?)"\)/g
Try this.Grab the captures.See demo.
http://regex101.com/r/qQ3kG7/1
Upvotes: 1
Reputation: 214949
For this particular string [^'"()]+(?=['")])
seems to work fine:
css = "url(image1.png), url('image2.png'), url(\"image3.png\")";
m = css.match(/[^'"()]+(?=['")])/g)
document.write(m)
In the general case, you have to resort to a loop, because JS doesn't provide a way to return all matching groups from a single call:
css = "url(image1.png), something else, url('image2.png'), url(\"image3.png\")";
urls = []
css.replace(/url\(['"]*([^'")]+)/g, function(_, $1) { urls.push($1) });
document.write(urls)
Upvotes: 2
Reputation: 7195
Try this:
var results = str.match(/url\(['"]?[^\s'")]+['"]?\)/g)
.map(function(s) {
return s.match(/url\(['"]?([^\s'")]+)['"]?\)/)[1];
});
Upvotes: 1
Reputation: 174696
You could try the below code also.
> var s = 'url(image1.png), url(\'image2.png\'), url("image3.png")';
undefined
> var re = /url\((["'])?((?:(?!\1).|[^'"])*?)\1\)/g;
undefined
> var matches = [];
undefined
> var m;
undefined
> while ((m = re.exec(s)) != null) {
......... matches.push(m[2]);
......... }
3
> console.log(matches)
[ 'image1.png', 'image2.png', 'image3.png' ]
Upvotes: 1