Split by the output of the regular expression "undefined"

I have code that retrieves query string parameters:

So (for example) if the window url is:

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

- First, the code uses split on & , and then split on =

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

And this is where my code got messed up.

the result is N4JOJ7yZTi5urACYrKW5QQ , and it should be N4JOJ7yZTi5urACYrKW5QQ==

Therefore, I increase my regex to:

search = so that after it ( there is no end OR there is no [=] )

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

it works. (you can run it on the console)

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

  • Why am I getting undefined
  • How can I cure my regex to get only ["a", "N4JOJ7yZTi5urACYrKW5QQ=="]

ps I know that I can replace all the finals = with something temporary, and then replace it back, but this tag is marked as a regular expression. So I'm looking for a way to fix my regex.

+4
source share
3 answers

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

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

However, you can always smooth out this match and remove the extra block:

 "a=N4JOJ7yZTi5urACYrKW5QQ==".split(/=(?!$|=)/); 
+5
source

URL must be encoded

 'a=N4JOJ7yZTi5urACYrKW5QQ==' 

it should be

 'a=N4JOJ7yZTi5urACYrKW5QQ%3D%3D' 

Take a look at encodeURIComponent()

And if you want to use the reg expression to get the key to the value

 > "abc=fooo".match(/([^=]+)=?(.*)?/); ["abc=fooo", "abc", "fooo"] 
+5
source

why should you use split? the match regular expression with two captures, for example /^(.+)=(.+)$/ , will seem more obvious.

+1
source

Source: https://habr.com/ru/post/1482432/


All Articles