2016-01-26 93 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

请检查这一个是否为你工作更好。我认为我的回答比图沙尔的建议更安全。 –