Reputation: 333
I have an application that stores the relative path of an image file in a DB. I need to remove any fully qualified URL from the path before I insert it into the database. I was using the following.
$('img', this).attr('src').replace(/https?:\/\/[^\/]+/, '');
However, this still puts the / in front of the image path
I start with this http://192.168.72.80/upload/11/img_3070.jpg
and I want to end up with this. upload/11/img_3070.jpg
The URL could be an IP, domain so I have to be able to deal with both scenarios.
Thanks
Upvotes: 0
Views: 1705
Reputation: 4652
var url='http://192.168.72.80/upload/11/img_3070.jpg';
var img=url.toString().match(/\/\/[^\/]+\/([^\.]+)/)[1];
EDIT 2:
var url='http://192.168.72.80/upload/11/img_3070.jpg?id=4';
var img=url.toString().match(/[^\/?#]+(?=$|[?#])/);
Upvotes: 1
Reputation: 253486
To get the path of the image element, assuming that the selector $('img', this)
returns the correct element, you could avoid regular expressions because, honestly, it avoids the problems that come with edge-cases in regular expressions, and simply use a created-<a>
element, and its attendant properties:
var a = document.createElement('a'),
images = document.images;
Array.prototype.forEach.call(images, function (img) {
a.href = img.src;
console.log(a.pathname);
});
Or, to use a function:
function retrievePathName (img) {
var a = document.createElement('a');
a.href = img.src;
return a.pathname;
}
var images = document.images;
Array.prototype.forEach.call(images, function (imgNode) {
console.log(retrievePathName(imgNode));
});
To use with the jQuery approach, you could:
var path = retrievePathName($('img', this).get(0));
Or:
var paths = $('img', this).map(function () {
return retrievePathName(this);
}).get(); // returns an array of relative paths to the 'paths' variable
References:
Upvotes: 1