1

I'm having a problem with replacing unnecessary character sets from a string. The following regex replaces the first occurrence of the character set "&=&" but doesn't take care of the leftovers. How does one replace the first and any consecutive occurences of a character set with regex?

var test = "var1=data1&var2=data2&=&=&=&=&var3=data3&=&=&var4=data4&var5=&var6=data6";
var result = "";
result = test.replace(/(\&\=\&)+/g, '&');

// Result returns "var1=data1&var2=data2&=&=&var3=data3&=&var4=data4&var5=&var6=data6"
4

2 回答 2

2

您可以改用积极的前瞻性。基本上,寻找&=,但只有那些后面跟着另一个&

var a = "var1=data1&var2=data2&=&=&=&=&var3=data3&=&=&var4=data4&var5=&var6=data6";
var b = a.replace(/\&=(?=\&)/g,'');
// b = var1=data1&var2=data2&var3=data3&var4=data4&var5=&var6=data6

(我认为这就是你所追求的)

于 2013-08-13T03:30:56.133 回答
1

而不是 (&=&)+,你需要的是 ([&=]+&)+

于 2013-08-13T03:40:37.893 回答