views:

32

answers:

3

Hi all,

I'd like to use a JS regex to take a string such as the following:

'http://www.somedomain.com/some_directory/some_other_directory/some_image.jpg'

And turn it into this:

'http://www.some_other_domain.com/another_directory/yet_another_directory/size1_some_image.jpg'

Any hints? Additionally, any pointers for books or other resources that give a gentle introduction to mastering regexes in JS and other languages?

A: 

-edit- Sorry didn't read propperly

Younes
You should delete this answer.
SLaks
A: 

This should probably do something similar to what you want.

regex literal: /http:\/\/www\.somedomain\.com\/some_directory\/some_other_directory/\/(.+?)\.jpg/g

Replacement: "http://www.some_other_domain.com/another_directory/yet_another_directory/size1_\1.jpg"

This assumes the image names are the only thing that is a variable in this expression, but also gives you the ability to use whatever replacement you want for the rest of the URL, so you could change it to https or ftp or whatever you need to.

This link should help as a Regex tester and reference, having info on and the ability to test three regex syntaxes: http://www.regextester.com/

...Though if the string you're working with is merely the URL itself, then as SilentGhost states, there's not really much of a use for regex here.

JAB
+1  A: 

In this case simple string method would do:

url = 'http://www.somedomain.com/some_directory/some_other_directory/some_image.jpg';
bits = url.split('/');
'http://abc.com/def/ghi/' + bits[bits.length-1]

regex of course would work too:

'http://abc.com/def/ghi/' + url.match(/\/([^\/]+)$/)[1]

but it's unnecessary.

SilentGhost
Going by what jerome said, that should be `'http://abc.com/def/ghi/size1_' + bits[bits.length-1]`.
JAB
@jab: as you've noticed jerome didn't use `abc.com/def/ghi` did he?
SilentGhost
@SilentGhost: `http://www.some_other_domain.com/another_directory/yet_another_directory/size1_` then, to use jerome's example URL and filename prefix.
JAB