开发者

need help with regex in javascript to replace string pattern

开发者 https://www.devze.com 2023-03-08 14:37 出处:网络
Need help with regex javascript , i tried few but didn\'t work i want to replace the the following string which is a url. The values 200, 400are dynamic in the below string

Need help with regex javascript , i tried few but didn't work

i want to replace the the following string which is a url. The values 200, 400 are dynamic in the below string

url=http://www.test.com?debug=true&MAXWIDTH:200+MAX开发者_开发技巧HEIGHT:400

with ,900 , 900 always and the result should be

after regex i want the url string contains the below value

url=http://www.test.com/?debug=true&MAXWIDTH:900+MAXHEIGHT:900


var replaceMaxWidthAndHeight = function(str, newWidthAndHeight) {
  var i=0;
  return str.replace(/\s*(MAXWIDTH|MAXHEIGHT)\s*:\s*(\d+)\s*/g, function(s, m1) {
    return m1 + ':' + newWidthAndHeight[i++];
  });
};

var s1 = "url=http://www.test.com/?debug=true&MAXWIDTH:200+MAXHEIGHT: 400";
var s2 = replaceMaxWidthAndHeight(s1, [900, 900]);
s2; // => "url=http://www.test.com/?debug=true&MAXWIDTH:900+MAXHEIGHT:900"
s2 = replaceMaxWidthAndHeight(s1, [10, 20]);
s2; // => "url=http://www.test.com/?debug=true&MAXWIDTH:10+MAXHEIGHT:20"


If you want replace it ignoring the order or if both are there:

str = str.replace(/(MAXWIDTH:|MAXHEIGHT:)\d+/g, '$1900');


If MAXWIDTH and MAXHEIGHT always appear in the url as MAXWIDTH:200+MAXHEIGHT:400, then this regex will work.

var string = "url=http://www.test.com?debug=true&MAXWIDTH:200+MAXHEIGHT:400";
string.replace(/MAXWIDTH:\d*\+MAXHEIGHT:\d*/, 'MAXWIDTH:900+MAXHEIGHT:900');


Replace

(url=http://www.test.com\?debug=true&MAXWIDTH:)\d*(\+MAXHEIGHT:)\d*

with

$1900$2900

(being $1 and $2 the back references to the matching groups

EDIT: Thanks to Rocket

string.replace(/(url=http:\/\/www.test.com\?debug=true&MAXWIDTH:)\d*(\+MAXHEIGH‌​T:)\d*/, '$1900$2900')


Or a more general solution:

function replaceValue(str, label, value) {
    rX = new RegExp("\\s*" + label + "\\s*:\\s*(\\d+)\\s*");
    return(str.replace(rX, label + ":" + value);
}

url = replaceValue(url, "MAXHEIGHT", 900);
url = replaceValue(url, "MAXWIDTH", 900);
0

精彩评论

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