最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Split by regex yield "undefined" - Stack Overflow

programmeradmin0浏览0评论

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.

Share Improve this question asked May 23, 2013 at 16:48 Royi NamirRoyi Namir 149k144 gold badges493 silver badges831 bronze badges 1
  • You can also use .filter(function(n){ return n; }) to remove empty matches. – km6zla Commented May 23, 2013 at 17:13
Add a ment  | 

3 Answers 3

Reset to default 5

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(/=(?!$|=)/);

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.

发布评论

评论列表(0)

  1. 暂无评论