0

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 Answer 1

0

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" />

Sign up to request clarification or add additional context in comments.

3 Comments

Did not work. It downloads with these characters I don't want :(
It's work fine, please Run Code Snipped
Yes, it works elegantly. Sorry for the confusion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.