Skip to content Skip to sidebar Skip to footer

Javascript Regex - How To Extract Last Word Before Path To Image

I want to use regex to extract the last word from a file path. For example, I have: /xyz/blahblah/zzz/abc-blah/def-xyz-color.jpg I want to extract the 'color' out of the path. Th

Solution 1:

Why could you just take substring rather than using regex?

var path=" /xyz/blahblah/zzz/abc-blah/def-xyz-color.jpg";
var lastHyphen = path.lastIndexOf("-");
var lastDot = path.lastIndexOf(".");
var extractedValue=path.substring(lastHyphen + 1, lastDot);

a more compact version will be

var extractedValue=path.substring(path.lastIndexOf("-") + 1, path.lastIndexOf("."));

Solution 2:

var matched = /-(\w+).jpg/i.exec('/xyz/blahblah/zzz/abc-blah/def-xyz-color.jpg')[1];

Solution 3:

Why use regex?

var a = '/xyz/blahblah/zzz/abc-blah/def-xyz-color.jpg'
    .split('/').pop()
    .split('-').pop()
    .split('.')[0];

console.log(a);

Solution 4:

What about

-(\w+)\.jpg

?

If you don't want to hardcode the extension, you can do:

-(\w+)\.\w+\b

Of course, that will match lots of things, but I'm assuming the text to be matched will be the url ;)

Edit: It will match two groups, and you need to take only the second one, so just access to the 1st index:

var text = '/xyz/blahblah/zzz/abc-blah/def-xyz-color.jpg';
var pattern = /-(\w+)\.\w+\b/;
var match = pattern.exec(text);
alert(match[1]);  // color

Or do it in one line like @Ryan suggested.

Solution 5:

Why not just

var path= "/xyz/blahblah/zzz/abc-blah/def-xyz-color.jpg";
/(?:([^-.]+?)\.[^.]+?$)/i.test(path);
var color = RegExp.$1;
alert(color);

Post a Comment for "Javascript Regex - How To Extract Last Word Before Path To Image"