Simple jQuery ".replace()" string not working with RegEx

Viewed 68

I trying to use .replace() to change everything between the two last slashes of this URL with "w270" but nothing happens. Am I doing something wrong? jsFiddle

<div class="post-outer">
<img src="https://1.bp.blogspot.com/-9h_QVOCOX1w/XvnuC9SucSI/AAAAAAAABJo/roFOy4Tgs64wSDtI9-dC9WyglJJdPz3fACK4BGAsYHg/w100/image.png"/>
</div>

// The RegEx target everything between the two last slashes
    $('.post-outer img').attr('src').replace(/[^\/]+(?=\/[^\/]*$)/, 'w270');
3 Answers

Replace returns a new string, it does not modify the original, you will need to assign the result back to the attribute.

const img = $('.post-outer img');
const url = img.attr('src').replace(/[^\/]+(?=\/[^\/]*$)/, 'w270');
img.attr('src', url);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="post-outer">
<img src="https://1.bp.blogspot.com/-9h_QVOCOX1w/XvnuC9SucSI/AAAAAAAABJo/roFOy4Tgs64wSDtI9-dC9WyglJJdPz3fACK4BGAsYHg/w100/image.png"/>
</div>

Try this:

let url = $('.post-outer img').attr('src');
$($('.post-outer img')[0]).attr('src', url.replace(/[^\/]+(?=\/[^\/]*$)/, 'w270'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="post-outer">
<img src="https://1.bp.blogspot.com/-9h_QVOCOX1w/XvnuC9SucSI/AAAAAAAABJo/roFOy4Tgs64wSDtI9-dC9WyglJJdPz3fACK4BGAsYHg/w100/image.png"/>
</div>
<div class="post-outer">
<img src="https://1.bp.blogspot.com/-9h_QVOCOX1w/XvnuC9SucSI/AAAAAAAABJo/roFOy4Tgs64wSDtI9-dC9WyglJJdPz3fACK4BGAsYHg/w100/image.png"/>
</div>

Using attr(attributeName, function) simplifies this since it exposes current value in the callback and will also loop over all matching selectors and perform same task on each instance

$('.post-outer img').attr('src', (_, curr) => curr.replace(/[^\/]+(?=\/[^\/]*$)/, 'w270'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="post-outer">
<img src="https://1.bp.blogspot.com/-9h_QVOCOX1w/XvnuC9SucSI/AAAAAAAABJo/roFOy4Tgs64wSDtI9-dC9WyglJJdPz3fACK4BGAsYHg/w100/image.png"/>
</div>
<div class="post-outer">
<img src="https://1.bp.blogspot.com/-9h_QVOCOX1w/XvnuC9SucSI/AAAAAAAABJo/roFOy4Tgs64wSDtI9-dC9WyglJJdPz3fACK4BGAsYHg/w100/image.png"/>
</div>

Related