javascript onclick获取没有路径的图像名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29182283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:58:00  来源:igfitidea点击:

javascript onclick get image name without path

javascriptimage

提问by Jani Bolkvadze

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

我需要从没有路径的 SRC 属性中复制图像的名称(名称 + 扩展名).. HTML:

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

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

JS:

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

这段代码克隆了图像的完整路径..路径不是静态的,所以我不能只剪掉“SRC”的其余部分..提前致谢

回答by Apul Gupta

You should try this code:

你应该试试这个代码:

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

Your JS function would be:

你的 JS 函数是:

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;
 }

回答by WebServer

document.getElementById("img1").src.split("/").pop().split(".")[0]

回答by nehal gala

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;
}