Imre Imre - 5 days ago 5
Javascript Question

Using JavaScript and Regex to extract 1 specific data from URL

I would like to get from an URL like these JUST the "test@gmail.com" (or whatever email will be in the URL) :


  • www.website.com/?email=test@gmail.com

  • www.website.com/?email=test@gmail.com&name=john

  • www.website.com/?name=john&email=test@gmail.com



My problem is to solve that all of these 3 cases can happen (so no other data, OR data after the email, OR data before the email).

Unfortunately I have zero Regex-Skills, but was able to get so far together these 2 things:

/email=(.*)/
/email=(.*)\&/


The 1st one works if the email is the ONLY data.
The 2nd one works just if there is another data after my email.

But as mentioned I need to make it work regardless of which of the 3 types above is the case.

Could you help me out please?

Thank you very much!

BTW, I need it for this:

var msg = window.location.href.match(/email=(.*)/);


(I'm searching for an answer for more than 2 hours, used Google, used Regex-Testers, checked out Cheat Sheets and read many StackOverFlow-Questions... But I can't solve it on my own.)

Answer

Try this regex: https://regex101.com/r/gMyqDa/1 It matches email patterns not just any characters after email=

Comments