Strip filename from image link

I have a variable that contains a relative link for the image. This image file name may have different lengths. For instance...

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

I would like to extract from this variable only the name of the file with the extension .jpg and without the previous path. So the first example above should return d-amazingamethyst

Jquery answer is preferable, but direct javascript is also suitable. Thanks

+4
source share
3 answers

JsFiddle Methods

This returns "file-only.my"

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

It will receive a substring starting from the index of the last / plus 1 (beginning of the file name) to the last index . by cutting off 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 it . in the file name, if you truncate index 0, it will get the wrong file name.

I use .pop to remove the last element in the array, which will be the file extension, then I join everything with . s.

+2
source
  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 split the string into an array with the divisor "/". This gives the last item as the file name. Again, I split the last element as a file name based on "."

here is the violin for him. http://www.jsfiddle.net/RFgRN/

+1
source

The jQuery expression validation link uses the Hugoware answer option.

 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 than using regex, but it's amazing how regex is useful. Always a good ability to have in your arsenal. I always test my regular expression with online validation tools. Here is one example: http://www.regular-expressions.info/javascriptexample.html

+1
source

All Articles