remove full path, keep filename only

19,009

Solution 1

You don't need jQuery for that, just plain old JavaScript will do :)

alert('http://localhost/wordpress/wp-content/uploads/filename.jpg'.split('/').pop());​​

In your case:

var filename = imgurl.split('/').pop();

Solution 2

you can use a regular expression in order to achieve this..

var file = imgUrl.replace(/^.*[\\\/]/, '');

Now the file would consist of only the file name ..

Solution 3

One further option:

var filename = imgurl.substring(imgurl.lastIndexOf('/') + 1);

JS Fiddle demo.

Solution 4

If you're pretty confident that the URLs don't have funny stuff like hashes or parameters, a regex like this would do it:

var filename = imgurl.replace(/^.*\/([^/]*)$/, "$1");

Also: don't forget to declare "imgurl" with var, and you should probably use .prop() instead of .attr() if your version of jQuery is 1.6 or newer:

var imgurl = jQuery('img', html).prop('src');

Also jQuery internally turns the two-argument form of the function into this:

var imgurl = jQuery(html).find('img').prop('src');

so you might as well code it that way.

Share:
19,009
Admin
Author by

Admin

Updated on June 24, 2022

Comments