Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
}
like image 370
user1219691 Avatar asked Feb 19 '12 21:02

user1219691


3 Answers

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();
like image 178
Andy Avatar answered Sep 19 '22 21:09

Andy


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

like image 27
Vivek Chandra Avatar answered Sep 22 '22 21:09

Vivek Chandra


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.

like image 45
Pointy Avatar answered Sep 21 '22 21:09

Pointy