简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM