I came across a piece of code like this:
btnHref.replace(/myCode=([^&]*)/, 'myCode=' + itm.MyCode);
I understand the replace function in general ([text to replace], [text to replace with])
However I do not quite understand what is going on with:
/myCode=([^&]*)/
It's looking for "myCode=", I'm assuming that the rest is a regular expression for any character after the '='.
However I am not getting my desired results..
Example:
var myParams = 'myCode=' + itm.ReportCode + '&myVersion=' + itm.ReportVersion;
if (btnHref.indexOf('myCode') > -1) {
btnHref = btnHref.replace(/myCode=([^&]*)/, myParams);
} else {
btnHref += btnHref.indexOf('?') > -1 ? '&' + myParams : '?' + myParams;
}
The first time through everything is good. (It hits the else statement)
However the second time through (it hits the first statement in the if) and I end up with a string of:
/MyController/MyAction?myCode=AAA&myVersion=1.1&myVersion=2.2
Am I misunderstanding what the regular expression is?
-
This is a great example of why you should never use regular expressions when you really need a parser. Query strings are more nuanced than they might seem, so I always recommend using a parsing library. I wrote one, although there are many others available.zzzzBov– zzzzBov2016年07月20日 16:53:34 +00:00Commented Jul 20, 2016 at 16:53
1 Answer 1
[^&]* matches any sequence of characters except &. So it replaces everything starting with myCode= up to, but not including, the first &. When you do it the second time, it leaves the part of btnHref after &myVersion=2.2 alone. As a result, you end up with two &myVersion= parameters, because you're inserting another one.
That replacement is intended to replace just the myCode parameter, not any others. You should use a separate operation to replace myVersion.
var newCode = 'myCode=code123';
var newVersion = 'myVersion=Version1.2';
var btnHref = '/MyController/MyAction';
if (btnHref.indexOf('myCode') > -1) {
btnHref = btnHref.replace(/myCode=([^&]*)/, newCode);
} else {
btnHref += btnHref.indexOf('?') > -1 ? '&' + newCode : '?' + newCode;
}
if (btnHref.indexOf('myVersion') > -1) {
btnHref = btnHref.replace(/myVersion=([^&]*)/, newVersion);
} else {
btnHref += btnHref.indexOf('?') > -1 ? '&' + newVersion : '?' + newVersion;
}
console.log(btnHref);
var newCode = 'myCode=codeXXX';
var newVersion = 'myVersion=Version2.2';
var btnHref = '/MyController/MyAction';
if (btnHref.indexOf('myCode') > -1) {
btnHref = btnHref.replace(/myCode=([^&]*)/, newCode);
} else {
btnHref += btnHref.indexOf('?') > -1 ? '&' + newCode : '?' + newCode;
}
if (btnHref.indexOf('myVersion') > -1) {
btnHref = btnHref.replace(/myVersion=([^&]*)/, newVersion);
} else {
btnHref += btnHref.indexOf('?') > -1 ? '&' + newVersion : '?' + newVersion;
}
console.log(btnHref);