views:

35

answers:

3

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.

The result must be: avatar.jpg

+3  A: 

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');
David Hedlund
Thank you. it is work.
Alexander.Plutov
A: 

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>
ppshein
+1  A: 

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( /^.+\// , '' ));
seanizer