0

I have a simple query string in my program:

?username=someone@email.com&fname=

I have come up with a regular expression that selects everything except the data I want:

[^a-zA-Z0-9.@]|(username|fname)

I am trying to use javascripts str.split() to split around everything that isn't actually data in the query, like so:

let userinfo = global.location.search.split(/[^a-zA-Z0-9.@]|(username|fname)/).filter(Boolean);

Unfortunately, when this runs, I get the following array:

['username', 'someone@email.com', 'fname'].

I expect just ['someone@email.com'] since "username" and "fname" should be split around from my regex.

I have tested this in https://regex101.com/ and it appears to work fine, so I'm not sure why it doesn't work in JS.

Any ideas?

Sajid Ansari
  • 155
  • 2
  • 12
  • When you have a capture group in the regular expression, they're copied into the result. – Barmar Oct 03 '19 at 21:48
  • Not quite sure I agree, in this situation I am asking about the regex and how it works with js. I know I could just split and loop through it like those suggestions, but it doesn't answer the question of why it doesn't work here. Also, since this isn't a "real" query string, I could change it to any format I wish. – Sajid Ansari Oct 03 '19 at 21:49
  • Not addressing your regex question, but there are better ways to parse a url: https://stackoverflow.com/questions/979975/how-to-get-the-value-from-the-get-parameters – benvc Oct 03 '19 at 21:50
  • @Barmar, that fixed it! I feel so dumb. the corrected regex is `[^a-zA-Z0-9.@]|username|fname` – Sajid Ansari Oct 03 '19 at 21:50
  • `split` seems like the wrong function here. Why not `query.match(/username=([^&]+)/)`? Generally, if you have to use `.filter(Boolean)` after a regex, something has gone wrong. – ggorlen Oct 03 '19 at 21:51
  • The linked questions show better ways to get query parameters. – Barmar Oct 03 '19 at 21:57

2 Answers2

2

When you have a capture group in the regexp used with .split() the captured strings are included in the resulting array.

If you need a group but don't want to include it in the result, use a non-capturing group (?:username|fname).

But there's no need for the group in this case at all. /xxx|(yyy|zzz)/ matches the same thing as /xxx|yyy|zzz/, they only differ in what they capture.

/[^a-zA-Z0-9.@]|username|fname/
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You need Regex for such tasks, you can use standard URLSearchParams API

let searchParams = "?username=someone@email.com&fname="

let parsed = new URLSearchParams(searchParams)

console.log(parsed.get('username'))
Code Maniac
  • 37,143
  • 5
  • 39
  • 60