2010-06-09 38 views
0

我想用JS正則表達式來採取一個字符串,如下列:正則表達式,更換道路資源,修改資源名稱

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

,把它變成這樣:

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

任何提示?此外,書籍或其他資源的任何指針,可以輕鬆地介紹如何在JS和其他語言中掌握正則表達式?

回答

0

這應該可以做些你想要的東西。

正則表達式文字:/http:\/\/www\.somedomain\.com\/some_directory\/some_other_directory/\/(.+?)\.jpg/g

更換:「http://www.some_other_domain.com/another_directory/yet_another_directory/size1_ \ 1.JPG」

這是假設圖像的名字是在這個表達式中的變量的唯一的事,也讓大家使用的能力無論您需要替換其他網址,您都可以將其更改爲https或ftp或任何您需要的內容。

此鏈接應有助於爲正則表達式測試儀和參考,具有對信息和測試三個正則表達式語法的能力:http://www.regextester.com/

...但如果你正在使用的字符串僅僅是URL本身,那麼正如SilentGhost所說的那樣,這裏對於正則表達式並沒有什麼用處。

1

在這種情況下,簡單的字符串的方法會做:

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] 

當然,正則表達式將工作太:

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

但它是不必要的。

+0

按照jerome的說法,這應該是''http://abc.com/def/ghi/size1_'+ bits [bits.length-1]'。 – JAB 2010-06-09 13:50:05

+0

@jab:你注意到jerome沒有使用'abc.com/def/ghi'嗎? – SilentGhost 2010-06-09 13:54:30

+0

'http:// www.some_other_domain.com/another_directory/yet_another_directory/size1_'然後,使用jerome的示例URL和文件名前綴。 – JAB 2010-06-09 14:15:07