Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split by regex yield "undefined"

I have a code which extract query string parameters :

So ( for example) if the window url is :

....&a=1&.....

--The code first using split on & and then do split on the =

however , sometimes we use base64 values , which can have extra finals ='s (padding).

And here is where my code is messed up.

the result is N4JOJ7yZTi5urACYrKW5QQ and it should be N4JOJ7yZTi5urACYrKW5QQ==

So I enhance my regex to :

search = such that after it -> ( there is no end OR there is no [=])

'a=N4JOJ7yZTi5urACYrKW5QQ=='.split(/\=(?!($|=))/)

it does work. ( you can run it on console)

but the result is ["a", undefined, "N4JOJ7yZTi5urACYrKW5QQ=="]

  • Why am I getting undefined
  • How can i cure my regex for yielding only ["a", "N4JOJ7yZTi5urACYrKW5QQ=="]

p.s. I know i can replace all the finals ='s to something temporary and then replace it back but this tag is tagged as regex. So im looking a way to fix my regex.

like image 679
Royi Namir Avatar asked Dec 20 '22 05:12

Royi Namir


1 Answers

This happens because you have additional match ($|=). You can exclude it from matching with ?::

"a=N4JOJ7yZTi5urACYrKW5QQ==".split(/=(?!(?:$|=))/);

However, you can always flatten that match and remove extra block:

"a=N4JOJ7yZTi5urACYrKW5QQ==".split(/=(?!$|=)/);
like image 118
VisioN Avatar answered Dec 22 '22 19:12

VisioN