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

2

3 Answers 3

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;
 }
Sign up to request clarification or add additional context in comments.

2 Comments

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
try jQuery, it will simplify DOM manipulation so that you can easily access elements without ID/CLASS.
7
document.getElementById("img1").src.split("/").pop().split(".")[0]

1 Comment

OP did want the extension, so you don't need the .split(".")[0] bit.
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.