Search code examples
jqueryjquery-selectorssrc

How replace a part of an object attibute using jQuery?


People, here I got some answers how to replace part of a HREF attribute of a link. Eventhough I didn't understand how the "////\"'s works.

I need to do the following: A code that replace, in each "A IMG", the SRC 1.bp.blogspot.com/_YfY-Tbu-shE/S3q2T9SJQxI/AAAAAAAAAI8/w0kTOPwaxqs/s1600-h/TELA%204.png to 1.bp.blogspot.com/_YfY-Tbu-shE/S3q2T9SJQxI/AAAAAAAAAI8/w0kTOPwaxqs/s1600/TELA%204.png. Resuming: remove the -h from the SRC.

Could also explain, with examples, the "////\"'s tricks please? (or a page that shows it - didn't understand the examples in jQuery page)

Thanks.


Solution

  • patrick provided a nice way of removing the "-h" from the URL, with the noted exception of problems that might occur if the pattern "-h" shows up elsewhere in the URL, but I wanted to see if I could help by showing this as part of a more complete solution.

    $(function() {
        $('img[src*="s1600-h"]').each(function() {
            var newSrc = $(this).attr('src');
            newStr = newSrc.replace(/-h/,'');
            $(this).attr('src', newSrc);
        });
    });
    

    What this does is look for all "img" tags with an src containing s1600-h. Then, using a simple regular expression replacement, we take out the "-h", and update the src accordingly. You can work on refining these patterns if you find that certain things need to change, like s1600 being different each time? Or if the "-h" needs to be more specific.

    Good luck!