user1486133
user1486133

Reputation: 1467

Regex or standard substring solution to remove Wordpress image sizing from filename

I need to remove the Wordpress width and height details from an image path using Javascript, rather than pulling it from the full image. E.g:

imagePath = "http://localhost:8888/test/wp-content/uploads/2016/12/P1010050-700x525.jpg"

I need to convert imagePath into imagePath = "http://localhost:8888/test/wp-content/uploads/2016/12/P1010050.jpg"

It is not always the same path, and not always a jpg, but it will always be -123x123 that needs to be removed.

Am I better off doing a regex expression for this (and if so, what pattern do I need?) or should I take the end after the last - off, and then take the file extension off, and then reconstruct the string with concatenation?

Upvotes: 1

Views: 87

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

The solution using String.prototype.replace() function with specific regex pattern:

var imagePath = "http://localhost:8888/test/wp-content/uploads/2016/12/P1010050-700x525.jpg",
    replaced = imagePath.replace(/\-[^-]+(\.\w+)$/, '$1');

console.log(replaced);

Upvotes: 2

Related Questions