remove full path, keep filename only

Trying to remove the full url that is being returned to imgurl:
Usually returns something like http://localhost/wordpress/wp-content/uploads/filename.jpg
or http://localhost/wordpress/wp-content/uploads/images/filename.jpg

I’d like to strip off everything except filename.jpg and return it to
ahng_photos_upload_image. Strip off everything to the last forward-slash.
How can I do that with Jquery?

window.send_to_editor = function(html) {
imgurl = jQuery('img',html).attr('src');
jQuery('#ahng_photos_upload_image').val(imgurl);
tb_remove();
}

Related posts

Leave a Reply

8 comments

  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();
    
  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 ..

  3. 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.

  4. Here is an answer that will work when your file name is like ./file.jpg

    var extension = fileName.slice((fileName.lastIndexOf(".") - 1 >>> 0) + 2);
    var baseName = fileName.replace(/^.*/([^/]*)$/, "$1");
    var path = fileName.replace(/(^.*/)([^/]*)$/, "$1");