views:

45

answers:

1

I need to take strings in the following format:

http:\/\/img.mypath.net\/time\/daily\/2010\/1006\/my_image_name.jpg

And convert them to this, using JavaScript:

http://www.mynewpath.com/i/daily/2010/1006/77_my_image_name.jpeg

I'm sure that someone more fluent in RegEx than I can give a terse solution.

+4  A: 

How about this?

var url = 'http:\/\/img.mypath.net\/time\/daily\/2010\/1006\/my_image_name.jpg';    
url = url.replace('\\/', '/'); // Replace \/ by /
url = url.replace('img.mypath.net/time', 'www.mynewpath.com/i'); // Replace domain and first path.
url = url.replace(/([^/]+)$/g, '77_$1'); // Prefix last path with `77_` (???)
alert(url);

The requirement around 77 is unclear, but if it's fixed, the above should do.

BalusC
There are more differences between the two URLs than simply the escaped backslashes. Thanks, though.
jerome
Your final regex can simply be `[^/]+$` with `77_$0` in the replacement side.
Peter Boughton
@jerome: That wasn't obvious in the original question. I updated my answer. @Peter: that's indeed better.
BalusC
(This comment editing can get confusing... wish SO did some form of notification.) :)
Peter Boughton
@BalusC You've been a great help so far, but running the code above alerts the following.http://www.mynewpath.com/i/daily/2010/1006/77_$0
jerome
@jerome: I reverted the fix after the comment of @Peter (which in theory should have worked!). It should now work.
BalusC
Great. TY very much, @BalusC.
jerome
You're welcome. Now I can finally go watch world cup football of Netherlands ;)
BalusC