4

I have a variable which holds a relative link for an image. This image link file name can have various lengths. For example...

/v/vspfiles/assets/images/d-amazingamethyst.jpg
/v/vspfiles/assets/images/cdacarbon.jpg  

I would like to extract from this variable only the filename with out the .jpg extention and without the preceeding path. So the first example above should return d-amazingamethyst

A Jquery answer is preferred but straight javascript is ok as well. Thanks

user357034
  • 10,731
  • 19
  • 58
  • 72

3 Answers3

2

Methods on jsFiddle

This returns "file-only.my"

var x = "/v/whatever/file-only.my.jpg";
x = x.substring(x.lastIndexOf("/")+1, x.lastIndexOf("."));

It is going to get the substring, starting from the index of the last / plus 1 (the beggining of the filename) until the last index of the ., cutting the extension.

You can also use the split function.

var x = "/v/whatever/file-only.my.jpg";
x = x.split("/");
x = x[x.length-1].split('.');
x.pop();
x.join(".");

But then you need to handle .s on the filename, if you cut by the index 0 it will get the wrong filename.

I use .pop to remove the last element on the array, which is going to be the file extension, then I join everything back with .s.

BrunoLM
  • 97,872
  • 84
  • 296
  • 452
  • I used the first example an it worked and seems relatively straight forward. No need to make it more complicated than that. Thanks for your answer!!! – user357034 Oct 02 '10 at 00:44
  • Deceptively simple answer, +1 (though the +1 was partially earned by just *not* using regex. I am, heartily, biased against such tools) =) – David Thomas Oct 02 '10 at 00:58
1
var v = "/v/vspfiles/assets/images/d-amazingamethyst.jpg";

var s = v.split("/");

var filename = s[s.length-1].split('.')[0];

alert(filename);

first i have split the string into a array with the delimeter "/" . This gives last element as filename. Again i have split the last element as filename on the basis of "."

here is the fiddle for it. http://www.jsfiddle.net/RFgRN/

sushil bharwani
  • 29,685
  • 30
  • 94
  • 128
1

Referencing Regular expression field validation in jQuery use a variant of Hugoware's answer.

var phrase = "/v/vspfiles/assets/images/d-amazingamethyst.jpg";
var reg = new RegExp("\/\S+\/",i);
phrase = phrase.replace(reg, "");
alert(phrase);

There are other ways rather than using a regular expression, but it's amazing how helpful regex can be. Always a good skill to have in your arsenal. I always validate my regex's using online validation tools. Here is one for example: http://www.regular-expressions.info/javascriptexample.html

Community
  • 1
  • 1
Bill
  • 2,623
  • 1
  • 27
  • 41
  • While I agree with you on the fact that reg exp solution is always helpful it tends to make be dizzy, lol, thanks for the tool as well!! – user357034 Oct 02 '10 at 00:52