2016-01-26 91 views
1

您好我一直在試圖找到並使用以下URL使用正則表達式

http://res.cloudinary.com/chathura-rupasinghe/image/upload/c_fill,h_1024,w_768/v1453555296/manhattan_stater.jpg

當你看到h_1024,w_768告訴形象應該如何更換寬度&高度的圖像替換URL之間的值當我從cdn請求時縮放。根據我的要求,這應該是通過腳本前調整大小多變(URL,{500,500})應該是下面的URL轉換爲

http://res.cloudinary.com/chathura-rupasinghe/image/upload/c_fill,h_500,w_500/v1453555296/manhattan_stater.jpg

這是到目前爲止我的代碼它並不完美是有可能解決任何方式這個問題

var url = "http://res.cloudinary.com/chathura-rupasinghe/image/upload/c_fill,h_1024,w_768/v1453555296/manhattan_stater.jpg"; 
 

 

 

 
var reg1 = /(\h_.*?\,)/gi; 
 

 

 
url = url.replace(reg1,"h_500,"); 
 

 
console.log(url);

+0

'url.replace(/ H_ \ d +/「h_500」)' – Tushar

+0

我也做該在/ upload /後僅替換令牌,以避免不匹配 –

+0

請參閱[this regex demo](https://regex101.com/r/fM9nD5/1)。 –

回答

0

你可以在這裏使用一個更具體的正則表達式(即不會取代h_1 in http://ite.com/h_2/upload/c_fill,h_1024,w_580):

/(\/upload\/[^\/]*\bh_)\d+(,w_)\d+/ 

並替換爲"$1" + my_height + "$2" + my_width

參見regex demo

var mywidth = "800"; 
 
var myheight = "600"; 
 

 
var re = /(\/upload\/[^\/]*\bh_)\d+(,w_)\d+/; 
 
var str = 'http://res.cloudinary.com/chathura-rupasinghe/image/upload/c_fill,h_1024,w_768/v1453555296/manhattan_stater.jpg'; 
 
var subst = '$1' + myheight + '$2' + mywidth; 
 
var result = str.replace(re, subst); 
 
document.write(result);

正則表達式匹配:

  • (\/upload\/[^\/]*\bh_) - 組1(具有$1在替換字符串背引用)匹配文字字符序列/upload/(與\/upload\/),隨後wi TH比/零個或多個字符的其他(有[^\/]*),然後接着在字邊界\b與文字序列h_
  • \d+ - 一個或多個數字
  • (,w_) - 第2組(以$2在後面提及的替換字符串)匹配一個逗號,後跟與字字符後以下劃線
  • \d+ - 一個或多個數字
+0

請檢查這一個是否爲你工作更好。我認爲我的回答比圖沙爾的建議更安全。 –