$(document).rea" /> $(document).rea" /> $(document).rea"/>

Javascript to type "alt" from image url omitting specific characters

51 Views Asked by At

The following script works but not as expected.

<img class="img" src="https://photoooo.com/Name-Name2.jpg" width="200" height="300" />
$(document).ready(function() {  
  $('img').each(function(){  
   var $img = $(this);
   var filename = $img.attr('src')  
     if (typeof attr == typeof undefined || attr == false){
        $img.attr('alt', filename.substring((filename.lastIndexOf('/'))+1, filename.lastIndexOf('.')));
    }  
  });  
 });

I would like to modify the script so that it fetches the name of the photo to "alt" from the url of the photo. Excluding characters: "-" and ".jpg".

1

There are 1 best solutions below

3
AudioBubble On

use the replace method to remove the specific characters from the filename before setting it as the alt attribute

$(document).ready(function() {  
  $('img').each(function(){  
    var $img = $(this);
    var filename = $img.attr('src')  
    if (typeof attr == typeof undefined || attr == false){
    console.log(filename)
        var altText = filename.substring((filename.lastIndexOf('/'))+1, filename.lastIndexOf('.'))
        altText = altText.replace("-", "").replace(".jpg", "")
        $img.attr('alt', altText);
        console.log(altText)
    }  
  });  
});
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <img class="img" src="https://cdn.pixabay.com/photo/2017/03/01/15/40/internationalwomensday-2108838_960_720.png" width="200" height="300" />