Reputation: 14250
I am trying to get the folder path from the src attribute.
<img src='project/image/test/grey.png'/>
I want to get something like 'project/image/test/'
Here is my codes but I am not sure what to do next.
var folder = $('img').attr('src');
Can someone help me out on this? Thanks a lot!
Upvotes: 0
Views: 56
Reputation: 207501
Split apart, remove last index, join back together
var parts = 'project/image/test/grey.png'.split("/");
parts.pop();
var path = parts.join("/");
var pathWithSlash = parts.join("/") + "/";
or
Match last / and everything after it and remove it
var path = 'project/image/test/grey.png'.replace(/\/[^\/]*$/,"");
var pathWithSlash = 'project/image/test/grey.png'.replace(/[^\/]*$/,"");
Match with regular expression
var path = 'project/image/test/grey.png'.match(/^(.*\/)/)[0];
Upvotes: 0
Reputation: 772
var folderArr = $('img').attr('src').split('/'),
folder = '';
folderArr.pop();
folder = folderArr.join('/');
Upvotes: 0
Reputation: 127
Hy,
simple and self explaining solution:
$(document).ready(function(){
var source = $('img').attr('src');
var array = source.split('/');
var output = "";
for(var i = 0; i< array.length-1;i++){
output += array[i]+"/";
}
alert(output);
});
Upvotes: 0
Reputation: 195972
Try with .lastIndexOf()
var fullpath = $('img').attr('src')
folder = fullpath.substr(0,fullpath.lastIndexOf('/')+1);
Upvotes: 1
Reputation: 26257
Use regex
var src = $('img').attr('src');
var reg = /[^\/]*$/;
var folder = src.replace(reg, ''); // project/image/test/
Upvotes: 0