Search code examples
javascriptprototypejs

How to get the filename and extension out of a URL?


I'm using prototype and trying to get the filename and extension out of a URL in the src attribute of an <img>. For example, I want to get colorch091001-black-2.jpg out of this:

<img id="small_img_src" src="http://127.0.0.1/magento162/media/catalog/product/cache/1/image/265x265/9df78eab33525d08d6e5fb8d27136e95/c/o/colorch091001-black-2.jpg">

I can get the src value with:

var img = $('small_img_src').src;

But how do I get just the filename and extension?


Solution

  • Try this, For pure JavaScript Solution

    <img id="small_img_src" 
         title="Royal Dress" alt="" 
         src="http://127.0.0.1/magento162/media/catalog/product/cache/1/image/265x265/9df78eab33525d08d6e5fb8d27136e95/c/o/colorch091001-black-2.jpg"
         style="display: block;" />
    
    var src = document.getElementById('small_img_src').src;
    alert(src.substring(src.lastIndexOf('/') + 1));