Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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');
like image 653
Kim Santos Avatar asked Mar 28 '26 19:03

Kim Santos


1 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>
like image 199
Adrian Brand Avatar answered Apr 01 '26 07:04

Adrian Brand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!