0

I have the following URL:


https://localhost:44300/products/5746ba28804136004d060002?email=abc@gmail.com

What I need is to get the value of email from the URL into a variable and then use it in a jQuery code:

var email= "getthequerystringhere"

Malik Kashmiri
  • 5,741
  • 11
  • 44
  • 80
  • 1
    http://stackoverflow.com/questions/19491336/get-url-parameter-jquery-or-how-to-get-query-string-values-in-js – Jaapze Jun 21 '16 at 07:18
  • 3
    http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript – Parwej Jun 21 '16 at 07:18

2 Answers2

3

window.location.search contains any query string in the current page's URL. You can strip off the ? at the beginning to get the part you want:

var queryString = window.location.search.replace(/^\?/, '');

If you already have the URL in a string, you can split it on the ?:

var queryString = url.split('?', 2)[1] || '';

Once you have the query string, you can split it on & and then on = to get the particular parameter you're looking for:

var url = 'https://localhost:44300/products/5746ba28804136004d060002?email=abc@gmail.com';
var queryString = url.split('?', 2)[1] || '';
// split query string into key/value pairs
var parameters = queryString
  .split('&')
  .map(function(param) {
    var pair = param.split('=', 2);

    return {
      name: decodeURIComponent(pair[0]),
      value: decodeURIComponent(pair[1] || '')
    };
  });

// get the parameter with name "email" if it exists
var emailParam = parameters.filter(function(param) {
  return param.name === 'email';
})[0];

var email = emailParam ? emailParam.value : null;

console.log(email);
JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • location.search is the best because it ignores the section of the URL before the `?` and also the hash fragment which follows the GET parameters (the part of the URL after `#` if it is present), so you can just get location.search and split using the & character, and you will get all GET parameters. – mastazi Jun 21 '16 at 07:20
  • queryString variable contains `email=abc@gmail.com` i only want abc@gmail.com in variable – Malik Kashmiri Jun 21 '16 at 07:25
  • @AhmedJalal Please see my updated answer. – JLRishe Jun 21 '16 at 07:27
  • thanks allot @JLRishe – Malik Kashmiri Jun 21 '16 at 07:35
0

You can do it like this:

var url = "https://localhost:44300/products/5746ba28804136004d060002?email=abc@gmail.com";
var email = url.split("?email=")[1];
Sahil
  • 3,338
  • 1
  • 21
  • 43