12

I need to copy the name of the image (name + extension) from SRC attribute without path.. HTML:

 <input type="text" id="result" /><br /><br />

 <img src="../some_folder/some_folder/photo_name.jpg" onclick="getName()" id="img1" />

JS:

 function getName() {
    document.getElementById("result").value = document.getElementById("img1").src;
 }

This code clones full path of the image.. Path is not static, so I can not just cut rest of "SRC".. Thanks in advance

  • Possible duplicate of [How to pull the file name from a url using javascript/jquery?](https://stackoverflow.com/questions/1302306/how-to-pull-the-file-name-from-a-url-using-javascript-jquery) – Liam Aug 02 '17 at 13:44
  • `new URL(document.getElementById("img1").src).pathname.split("/").pop()` in 2021. – Sebastian Simon Apr 04 '21 at 07:57

3 Answers3

24

You should try this code:

var filename = fullPath.replace(/^.*[\\\/]/, '');

Your JS function would be:

function getName() {
     var fullPath = document.getElementById("img1").src;
     var filename = fullPath.replace(/^.*[\\\/]/, '');
     // or, try this, 
     // var filename = fullPath.split("/").pop();

    document.getElementById("result").value = filename;
 }
Apul Gupta
  • 3,044
  • 3
  • 22
  • 30
  • One more question please: I'm new in javascript. What if I can not define ID for the IMG, how can I do somethis like this: var fullPath = this.src; i need it, because I have several photos –  Mar 21 '15 at 11:53
  • try jQuery, it will simplify DOM manipulation so that you can easily access elements without ID/CLASS. – Apul Gupta Mar 21 '15 at 16:40
6
document.getElementById("img1").src.split("/").pop().split(".")[0]
Liam
  • 27,717
  • 28
  • 128
  • 190
WebServer
  • 1,316
  • 8
  • 12
3
function getName() {

    var fullPath = document.getElementById("img1").src;
    var index = fullPath.lastIndexOf("/");
    var filename = fullPath;
    if(index !== -1) {     
        filename = fullPath.substring(index+1,fullPath.length);
    }
    document.getElementById("result").value = filename;
}
Liam
  • 27,717
  • 28
  • 128
  • 190
nehal gala
  • 131
  • 1
  • 8