Search code examples
jqueryreplacefindsrc

Jquery replace with regex: replacing an attribute in SRC with another attribute


I'm using Google Static Maps, which loads an image map:

<img src="http://maps.google.com/maps/api/....&someparameter&someparameter&scale=1">

Notice the "scale=1" parameter at the end. I need to replace it with "scale=2" only on high density displays with WebKit to load a high resolution version from Google.

I'm using this find/replace script on DOM load with a condition, and it doesn't work. The window.devicePixelRatio works in WebKit (tested); but something is probably wrong with the function inside the if condition.

$(function()
    {
        if (window.devicePixelRatio >= 1.5)
        {
            $('img[src*="scale=1"]').each(function() {
                var newSrc = $(this).attr('src');
                newStr = newSrc.replace('/scale=1/','scale=2');
                $(this).attr('src', newSrc);
            });
        }
        else
        {
        }   
    });    

Thanks for suggestions!


Solution

  • It looks like you're getting the src attribute value, storing it into a variable called newSrc, then replacing the scale=1 and storing the result in newStr, then you're setting the src attribute of the image to newSrc, the original value?

    Shouldn't it be:

    $('img[src*="scale=1"]').each(function() {
        var newSrc = $(this).attr('src');
        newSrc = newSrc.replace('scale=1','scale=2');
        $(this).attr('src', newSrc);
    });