javascript - Get source of image - Stack Overflow

I have a next string like: <img src="..uploladmissionranksavatar.jpg' . $row[$c_name]

I have a next string like:

<img src="../uplolad/mission/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.

The result must be: avatar.jpg

I have a next string like:

<img src="../uplolad/mission/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.

The result must be: avatar.jpg

Share Improve this question edited Aug 19, 2010 at 7:48 Justin Johnson 31.3k7 gold badges66 silver badges89 bronze badges asked Aug 19, 2010 at 6:57 Alex PliutauAlex Pliutau 21.9k28 gold badges114 silver badges144 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

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:

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');

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>

Here's a shorter variation of David Hedlund's answer that does use regex:

var myImage = document.getElementById('imgAvatar'); // or whatever means of access
alert(myImage.src.replace( /^.+\// , '' ));

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743759263a4502321.html

相关推荐

  • javascript - Get source of image - Stack Overflow

    I have a next string like: <img src="..uploladmissionranksavatar.jpg' . $row[$c_name]

    6天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信