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.
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.
-
You can also use
.filter(function(n){ return n; })
to remove empty matches. – km6zla Commented May 23, 2013 at 17:13
3 Answers
Reset to default 5This 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(/=(?!$|=)/);
The url needs to be encoded
'a=N4JOJ7yZTi5urACYrKW5QQ=='
should be
'a=N4JOJ7yZTi5urACYrKW5QQ%3D%3D'
Look into encodeURIComponent()
And if you want to use a reg expression to get the key from the value
> "abc=fooo".match(/([^=]+)=?(.*)?/);
["abc=fooo", "abc", "fooo"]
why must you use split? a regex match with two captures, like /^(.+)=(.+)$/
would seem more obvious.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745157617a4614218.html
评论列表(0条)