javascript 获取图片来源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3519443/
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
Get source of image
提问by Alex Pliutau
I have a next string like:
我有一个下一个字符串,如:
<img src="../uplolad/commission/ranks/avatar.jpg' . $row[$c_name] .'" width="50" height="50"/>
How can i get a image file name in javascript? I know only PHP regexes. Extention of a file can be different.
如何在javascript中获取图像文件名?我只知道 PHP 正则表达式。文件的扩展名可以不同。
The result must be: avatar.jpg
结果必须是: avatar.jpg
回答by dxh
Regex is not ideal for this. JavaScript can traverse the HTML as distinct objects more readily than as a long string. If you can identify the picture by anything, say by adding an ID to it, or an ID to a parent with that as the only image, you'll be able to access the image from script:
正则表达式对此并不理想。与长字符串相比,JavaScript 可以更容易地将 HTML 作为不同的对象遍历。如果您可以通过任何方式识别图片,例如通过向其添加 ID,或将 ID 作为唯一图像添加到父级,您将能够从脚本访问该图像:
var myImage = document.getElementById('imgAvatar'); // or whatever means of access
var src = myImage.src; // will contain the full path
if(src.indexOf('/') >= 0) {
src = src.substring(src.lastIndexOf('/')+1);
}
alert(src);
And if you want to edit, you can do that just as well
如果你想编辑,你也可以这样做
myImage.src = src.replace('.jpg', '.gif');
回答by PPShein
Fetch it following coding which can help what you want to get.
在编码之后获取它,这可以帮助您获得想要的东西。
<script type="text/javascript">
function getImageName(imagePath) {
var objImage = new RegExp(/([^\/\]+)$/);
var getImgName = objImage.exec(imagePath);
if (getImgName == null) {
return null;
}
else {
return getImgName[0];
}
}
</script>
<script>
var mystring = getImageName("http://www.mypapge.mm/myimage.png")
alert(mystring)
</script>
回答by Sean Patrick Floyd
Here's a shorter variation of David Hedlund's answerthat does use regex:
这是使用正则表达式的David Hedlund 答案的较短变体:
var myImage = document.getElementById('imgAvatar'); // or whatever means of access
alert(myImage.src.replace( /^.+\// , '' ));

