Reputation: 13517
Input URL: http://somewpsite.com/wp-content/uploads/2012/10/IMG_1234-150x150.jpg
Expected Output URL: http://somewpsite.com/wp-content/uploads/2012/10/IMG_1234.jpg
Current Regex: $(this).attr('src').replace('/-[\d]+x[\d]+/', '');
Assume $(this)
represents an img
element. I know I could just as easily use -150x150
as the replacement string, but there are different sizes and it should be capable of supported even more sizes without the need to come back and edit this code.
I'm hoping someone here can figure out what's wrong with my current regex above.
Upvotes: 0
Views: 688
Reputation: 220136
What's wrong is that in JavaScript regex's aren't strings, so you don't wrap them in quotes.
Note that you don't need the brackets around the \d
:
$(this).prop('src', function (i, v) {
return v.replace(/-\d+x\d+\.jpg$/, '.jpg');
});
If you might also be using other image formats, use this instead:
$(this).prop('src', function (i, v) {
return v.replace(/-\d+x\d+\.(jpg|png|gif)$/, '.$1');
});
Upvotes: 4
Reputation: 44289
Regexes are specific literals in JavaScript, they are not created as strings. Simply remove the single quotes:
$(this).attr('src').replace(/-[\d]+x[\d]+/, '')
Note that replace
does not work in-place but returns the resultant string instead. So depending on whether you want to process it further or just write it back into the attribute, you will have to assign this to something.
Upvotes: 2