1

I have an image that gets placed on the page, and the dimensions are different depending on the image that is chosen. I'd like to use regex to replace the image dimensions so that they are always 200x200, but I'm not sure how to go about doing so. The image dimensions are apart of a string.

Example:

http://www.site.com/path/to/image/The-fly-300x194.jpg

but I'd like to have it be:

http://www.site.com/path/to/image/The-fly-200x200.jpg

I'm not sure how to go about changing that using regex. I could use str.replace or whatever, but the dimensions are different depending on the image.

bjb568
  • 9,826
  • 11
  • 45
  • 66
EHerman
  • 1,563
  • 6
  • 27
  • 48
  • 3
    Which tool are you using for regex? – anubhava Apr 08 '14 at 19:37
  • 1
    The image dimensions are also inside the JPEG datastream so you need to rewrite the JPEG as well as giving the file a new name. – Glenn Randers-Pehrson Apr 08 '14 at 19:39
  • 1
    What language? What do you need replaced? Multiple images? One image? In a container? All in document? Do you know where it is? Do you know the format of the image? Unclear what you're asking. – bjb568 Apr 08 '14 at 19:39
  • 1
    Don't want to take too much about the actual regex for this, but the idea would be to use capture groups in the form of "^(.*)(\d+)x(\d+).jpg$" you could then reconstruct the url with the first capture group and your newly desired dimensions. – photoionized Apr 08 '14 at 19:42

1 Answers1

1

In Javascript:

var s = 'http://www.site.com/path/to/image/The-fly-300x194.jpg';
var r = s.replace(/[^.-]+(?=\.jpg)/, "200x200");
//=> http://www.site.com/path/to/image/The-fly-200x200.jpg
anubhava
  • 664,788
  • 59
  • 469
  • 547
  • 1
    Seems to be working perfectly. Any tips on where/how to go about learning proper regex. Seems like a task only a wizard can handle... – EHerman Apr 08 '14 at 19:42
  • 1
    I think http://www.regular-expressions.info/ is pretty good resource for learning regex. – anubhava Apr 08 '14 at 19:44
  • Awesome, going to take a look. Would love to be able to regex off the top of my head (or at least close to it). Thanks anubhava! – EHerman Apr 08 '14 at 19:45