I need help with a regexp to get only the code parameter from this url:
URL: code=4%2FsAB_thYuaw3b12R0eLklKlc-qcvNg6f8E8pgvu_02MTTJE0NOcyvXkrTQrB3QK8209wSbIpLDEBrk8vUGYKQ41I&scope=https:.....
My Code:
getParameterByName(name) {
var url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$|)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
this piece of code is returning `
4/sAB_thYuaw3b12R0eLklKlc-qcvNg6f8E8pgvu_02MTTJE0NOcyvXkrTQrB3QK8209wSbIpLDEBrk8vUGYKQ41I
In this case i need the first and only backslash to be a % sign instead..
I can't get it to work.
Thnx in advance!
asked Dec 11, 2018 at 3:50
-
Not sure I fully understand what you are trying to do but if you just want everything between "code=" and the next "&" try "code=([^&]*)" I assume you have a reason for not doing this, if so, sorry.Mark– Mark2018年12月11日 04:02:41 +00:00Commented Dec 11, 2018 at 4:02
3 Answers 3
It works for me!!!
function getUrlParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
answered Dec 11, 2018 at 4:24
2 Comments
Luis Estevez
I like this because you answered it in the format of KENUBBE despite the fact KENUBBE can do this with one regex without using replace or any other operation.
Mark
That's why I was confused by the question - his code is so overly complicated I thought I must be missing something.
Untested JavaScript regex:
var myRe = /=(.*)&/igm
var url = 'code=4%2FsAB_thYuaw3b12R0eLklKlc-qcvNg6f8E8pgvu_02MTTJE0NOcyvXkrTQrB3QK8209wSbIpLDEBrk8vUGYKQ41I&scope=https:';
var code = myRe.exec(url);
answered Dec 11, 2018 at 4:02
Comments
Use \bcode=([^&]+)
. It's sure to grab code query using word boundary 'code=' then capture any characters until it reaches &
or the end.
test regex here: https://regex101.com/r/eSnB4S/1
answered Dec 11, 2018 at 4:45
6 Comments
Mark
Does the {1,} add anything to just * ?
Luis Estevez
@Mark yes.
{1,}
makes sure it matches between one and unlimited. *
can match between zero and unlimited. So if you use *
quantifier instead, and have test case code=
you will have an empty string in capture group. So having {1,}
helps prevent that empty string.Code Maniac
@LuisEstevez well
+
does the same thing {1,}
. so you can use +
if you want to match one or more. demo regex101.com/r/eSnB4S/2 Luis Estevez
@CodeManiac Ahh, yes thanks! I'll use that for now on :)
Mark
I know that, I'm just looking for a real world case where that matters here. The only difference would be where code=&... my version produces an empty match group and yours produces no match. But that is also a malformed url with queries so...
|
lang-js