Reputation: 2033
with javascript regex I´m trying to get the image name and extension as capture group of css properties.
Requirements
Example:
behavior: url(#default#VML); -> ignored wrong ending
background-image: url(dog.ttf); -> ignored wrong ending
background-image: url('cat.png'); -> cat.png
background-image: url(bird.gif); -> bird.gif
background-image: url('../monkey.png'); -> monkey.png
background-image: url('../../rab$bit.png'); -> rab$bit.png
background-image: url('../animal/cow.jpg'); -> cow.jpg
This is what I have so far:
url(?:\(\"|\(\'|\(\/?.*\/|\()(\.+)?(\/.*\/)?(\w*)+(.png|.jpg|.gif|.jpeg)
https://regex101.com/r/3mMdTI/6
Unfortunately due to the '\w' group this breaks when a filename has digits or characters like $. Can one suggest a better solution?
Upvotes: 1
Views: 1414
Reputation: 7476
I am assuming you are asking for image name with format only not path and other thing.
var string = `behavior: url(#default#VML);
background-image: url(dog.ttf);
background-image: url('cat.png');
background-image: url(bird.gif);
background-image: url('../monkey.png');
background-image: url('../../rab$bit.png');
background-image: url('../animal/cow.jpg');`
var result = string.match(/[\w\.\$]+(?=png|jpg|gif)\w+/g)
console.log(result)
Upvotes: 2
Reputation: 749
try this:
var string = `behavior: url(#default#VML);
background-image: url(home_bbbbbb_14.ttf);
background-image: url('home.ttf');
background-image: url('home.png');
background-image: url(images/home_bbbbbb_14.png);
background-image: url('images/home_bbbbbb_14.jpeg');
background-image: url("images/home_bbbbbb_14.png");
background-image: url(home_bbbbbb_14.png);
background-image: url('home_bbbbbb$_14.png');
background-image: url("home_bbbbbb_14.png");
background-image: url("../img/home_bbbbbb_14.png");
background-image: url("./img/home_bbbbbb_14.png");
background-image: url("../../img/home_bbbbbb_14.jpg");
url("images/animated-overlay.gif");
url("images/ui-bg_flat_75_ffffff_40x100.png");
url('select2.png');
url(select2x2.png);
url('../images/back_enabled.png');
url('../pic/back_enabled.png');`
var result = string.match(/(?!url)([^\/('"\\]+)\.(?=png|jpg|gif|jpeg)('|"|)\w+/g)
console.log(result)
Upvotes: 0
Reputation: 471
try this:
(.*\/)?(.*?.(png|jpg|jpeg|gif)$)
2nd group will be image name
Upvotes: 0
Reputation: 1964
Hope you like this one:
var rx = /([^\/('"\\]+)\.(jpg|png|jpeg|gif)/i
In the square brackets I put all chars that are not supposed to be in the name of the image /, \, ', ", (
You may add or remove according to your needs.
Upvotes: 1