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.

5
  • So the "V" turns intto "/" and the "W" turns into "www" right? Commented Jul 6, 2010 at 17:07
  • that's \/\/ not W. Though it does look like the domain should change from "img.mypath.net" to "www.mynewpath.com" - again, a straight replace can do that. Commented Jul 6, 2010 at 17:13
  • 2
    Where does the 77 come from? Also, do you have literal backslash characters in your data or not? Because a JavaScript string literal containing "\/" is the same as one containing "/". Commented Jul 6, 2010 at 17:14
  • I've just edited to convert both to code format (prefix with four spaces, or quote with backticks), to make characters clear. At the same time I removed double quotes, which I assume were not needed, but noting here in case that's relevant Commented Jul 6, 2010 at 17:18
  • 1
    I'd like to know the citeria for the 77 before giving a reasonable answer. Commented Jul 6, 2010 at 17:19

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

7 Comments

There are more differences between the two URLs than simply the escaped backslashes. Thanks, though.
Your final regex can simply be [^/]+$ with 77_$0 in the replacement side.
@jerome: That wasn't obvious in the original question. I updated my answer. @Peter: that's indeed better.
(This comment editing can get confusing... wish SO did some form of notification.) :)
@BalusC You've been a great help so far, but running the code above alerts the following. mynewpath.com/i/daily/2010/1006/77_$0
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.