Rob
Rob

Reputation: 333

Remove full URL from Image path jquery

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

Answers (2)

dm4web
dm4web

Reputation: 4652

var url='http://192.168.72.80/upload/11/img_3070.jpg';

var img=url.toString().match(/\/\/[^\/]+\/([^\.]+)/)[1];

http://jsfiddle.net/040o8zt0/

EDIT 2:

var url='http://192.168.72.80/upload/11/img_3070.jpg?id=4';
var img=url.toString().match(/[^\/?#]+(?=$|[?#])/);

Upvotes: 1

David Thomas
David Thomas

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);
});

JS Fiddle demo.

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));
});

JS Fiddle demo.

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

Related Questions