0

Given the following URL:

https://example.com/test/results/?usp-custom-14=2015+2017&usp-custom-8=United-States

How can I save three vars:

var date1: "2015";
var date2: "2017";
var loc = "United States";

Note: we have two dates with a + symbol in the url 2015+2017 and we need to split them. And has a dash in the url United-States and we need it as United States

This is what I am trying:

function getUrlVars() {
  var vars = [], hash;
  var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
  for(var i = 0; i < hashes.length; i++) {
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
  }
  return vars;
}
var dates = getUrlVars()["usp-custom-14"];
var loc = getUrlVars()["usp-custom-8"];
var dateSplit = dates.split("+");

Also, I need to update the URL again for other reasons once the page is loaded, and I do:

history.replaceState('data to be passed', 'Title of the page', '<?php echo getAddress(); ?>/?usp-custom-14='+dateSplit+'&usp-custom-8='+loc);

But the url is duplicated

https://example.com/test/results/?usp-custom-14=2015+2017&usp-custom-8=United-States/?usp-custom-14=2015,2017&usp-custom-8=United-States
rob.m
  • 9,843
  • 19
  • 73
  • 162
  • Possible duplicate of [Access GET directly from JavaScript?](https://stackoverflow.com/questions/1586330/access-get-directly-from-javascript) – Eddie Jun 06 '18 at 02:47
  • @Eddie it's not really a duplicate, I have provided my take on the solution and I also have different needs as per saving the vars and update the url – rob.m Jun 06 '18 at 02:48
  • 1
    If you are looking for improvements of an existing solution, take a look at https://codereview.stackexchange.com. – Script47 Jun 06 '18 at 02:49
  • @Script47 I am not looking for an improvement, there is a bug as per the url being duplicated once updated as per what my question says. – rob.m Jun 06 '18 at 02:49
  • What is the bug? If your solution has a bug and there is an exiting answers on the same question, I think it is a duplicate. :) – Eddie Jun 06 '18 at 02:51
  • @Eddie I don't see any solution in what You linked. guys, if you don't want or can't help don't get over it, I am only looking for an help. Thanks – rob.m Jun 06 '18 at 02:52
  • 1
    @rob.m if people are confused as to what you are trying to say, consider clarifying the question. – Script47 Jun 06 '18 at 02:52
  • Is `getAddress()` returning query string? – Thum Choon Tat Jun 06 '18 at 02:52
  • 1
    probably the first of the duplicates is coming from `` – csum Jun 06 '18 at 02:53
  • @Script47 I agree with you but then please ask me to clearify and I will do, don't send me to other links because i can assure you I have being everywhere before to post on here – rob.m Jun 06 '18 at 02:53
  • Possible duplicate of [How to get the value from the GET parameters?](https://stackoverflow.com/questions/979975/how-to-get-the-value-from-the-get-parameters) – Script47 Jun 06 '18 at 02:54
  • @ThumChoonTat it is indeed – rob.m Jun 06 '18 at 02:54
  • @Script47 I know about the search par, but I don't want to search as I don't know the value, I need to split after certain part of the url... – rob.m Jun 06 '18 at 02:55
  • Remove query string from `getAddress()` should solve the problem? – Thum Choon Tat Jun 06 '18 at 02:56
  • Why not you just use window.location.href.split('?')[0] to get address without using ? – Terry Wei Jun 06 '18 at 02:56
  • @TerryWei because I didn't know I could get the url using that but I knew with php.. will try now – rob.m Jun 06 '18 at 02:57
  • @TerryWei yup, that's better.. thanks – rob.m Jun 06 '18 at 02:59
  • OK, that's fine. As their comment above, just need to figure out what happened to getAddress function using javascript or just modify this php function are both OK – Terry Wei Jun 06 '18 at 03:01

3 Answers3

2

You can split the url on ? and use pop() to return the last member of the resulting array, which would be the entirety of your query string.

From there, you could split it into key-value pairs by splitting it first on &, and then on =.

I've put this in a function so that you can simply do getParam("my-url-parameter") when needed. Using this, and then handling the + and - on your specific parameters, you should be able to get what you want quite easily.

It should also be reusable wherever needed.

function getParam(key) {
    //var url = window.location.href;   (Doesn't work on StackOverflow, but would be used in your real environment)
    var url = "https://example.com/test/results/?usp-custom-14=2015+2017&usp-custom-8=United-States";
    var querystring = url.split("?").pop();
    var params = {};
    querystring.split("&").forEach((i) => params[i.split("=")[0]] = i.split("=")[1]); //Create key-value pairs
    return params[key] || null;
}

var uspCustom14 = getParam("usp-custom-14").split("+");
var date1 = uspCustom14[0];
var date2 = uspCustom14[1];
var country = getParam("usp-custom-8").replace(/\-/g, ' ');

console.log(`Date 1: ${date1},`, `Date 2: ${date2},`, `Country: ${country}`);

For your second issue, you can remove the query string and re-add it with the proper values:

var urlDates = getParam("usp-custom-14").replace('+',',');
var urlCountry = getParam("usp-custom-8");
history.replaceState('data to be passed', 'Title of the page', `${window.location.href.split("?")[0]}?usp-custom-14=${urlDates}&usp-custom-8=${urlCountry}`);
Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
  • @rob.m As indicated by the comments, make sure to remove my `var url` line, and replace it with the one I've commented out instead. In your version you'll want to use `window.location.href`, however this will *not* work on StackOverflow. – Tyler Roper Jun 06 '18 at 03:22
  • yup sure, trying now, just remember to include the last bit `history.replaceState('data to be passed', 'Title of the page', url + '?usp-custom-14='+date1 date2+ +'&usp-custom-8='+country);` as per the question, for other reasons i need to replace again the url – rob.m Jun 06 '18 at 03:24
  • Your duplication issue is not being caused by any of the code in your question. It's likely in your PHP `getAddress()` function. – Tyler Roper Jun 06 '18 at 03:26
  • @yeah I know, removed that php bit. But i still need to repopulate it.. – rob.m Jun 06 '18 at 03:27
1

This should give you what you want while keeping it as close to your original code as I could. You can safely split a string with a "+" in it. You had the "?" and "=" splits in the wrong order.

function getUrlVars() {
  var vars = [], hash;  
  var hashes = window.location.href.split('?')[1];
  var params = hashes.split('&');    
  for(var i = 0; i < params.length; i++) {  
     hash = params[i].split('=');
     vars.push(hash[0]);
     vars[hash[0]] = hash[1];    
}
return vars;
}
var dates = getUrlVars()["usp-custom-14"];
var loc = getUrlVars()["usp-custom-8"];
var dateSplit = dates.split("+");
Victor Stoddard
  • 3,582
  • 2
  • 27
  • 27
0

var str ="https://example.com/test/results/?usp-custom-14=2015+2017&usp-custom-8=United-States";
var split = str.split('usp-custom-14=');
var firstDate = split[1].split('+')[0];
var secondDate = split[1].substring(split[1].lastIndexOf("+")+1,split[1].lastIndexOf('&'));
var country = split[1].substring(split[1].lastIndexOf("=")+1,split[1].length-1).replace('-',' ');

console.log(firstDate);
console.log(secondDate);
console.log(country);
Aakash
  • 155
  • 1
  • 3
  • 11
  • Hmmm. This answer **(A)** Provides *zero* context **(B)** Removes the last letter of the country **(C)** Will break if the query parameters are in any other order than this exact case. – Tyler Roper Jun 06 '18 at 03:15
  • @TylerRoper the context I understand it as I can read what it does, you're right about the last letter tho, didn't notice it. Can you fix it? – rob.m Jun 06 '18 at 03:17
  • @TylerRoper for my case, the order will always be that one. Do you have any other way to do it? Thanks – rob.m Jun 06 '18 at 03:18
  • @rob.m I don't agree with this answer so I'm not going to fix it. I submitted an alternative answer, though at this point you've already accepted this one - I don't want to pander for the reputation points so I won't ask you to accept mine, but for your own sake, I'd consider implementing it over this one. – Tyler Roper Jun 06 '18 at 03:18
  • @TylerRoper tbh, I removed the accepted mark as I didn't notice the last letter bug, I can't see your answer tho, it might be better and I hope it is but where is it? – rob.m Jun 06 '18 at 03:19