0

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

2 Answers 2

1
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(/[^\/?#]+(?=$|[?#])/);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks but now it's removing the .jpg from the end of the image URL I am getting this upload/AA/img_3074
I'm sorry, I did not check the result. I added a new solution.
1

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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.