开发者

Regex, replace path to resource, modify resource name

开发者 https://www.devze.com 2023-01-03 08:18 出处:网络
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\'

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 resource开发者_运维百科s that give a gentle introduction to mastering regexes in JS and other languages?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消