strip filename from image link
I have a variable which holds a开发者_Python百科 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
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.
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/
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
精彩评论