How to save strings from part of url?

how to pass parameter in url in javascript
passing parameters in url html
how to pass parameter in url in php
how to pass # in url query string
pass query string in url php
url parameters
url variables
how to pass post parameters in a url

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

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}`);

Use URL Variables to Pass Data, URL Variables make for a quick method for pre-populating existing data into a survey. the end of the survey link, data can be stored as part of each survey response. If the query string variable was STORE, the above merge code would still  World's simplest string tool Free online string URL-encoder. Just load your string and it will automatically get URL-escaped. There are no ads, popups or nonsense, just a string URL-escaper.

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("+");

How to extract part of the URL path with Google Tag Manager , In the next step, let's return that pageUrl but only a part of it. We can do that with the split() method, which splits a string (in this case, URL) into  If you want to get the parameters from a url in a Windows Store App you need to use WwwFromUrlDecoder. You create an object from this class with the query string you want to get the parameters from, the object has an enumerator and supports also lambda expressions.

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);

How to Get a Query String From a URL, Sometimes this data is passed as part of the URL string, so you may therefore need to retrieve a portion of the URL within a Web page script. Web scripts can be  Url Decode. Online tool for url encoding a string. Convert text into a url decoded string using this free online url decoder utility.

Creating URL query strings in Python, How to make Python do the tedious work of creating URL query strings. the ? , which is always used to set off the query string from the first part of the URL. Looking a manipulating query strings on a website to change the information changed on the page. https://learn-the-web.algonquindesign

Query string, On the World Wide Web, a query string is the part of a uniform resource locator (​URL) which if the user saves or sends the URL to another user; cookies can be maintained across browsing sessions, but are not saved or sent with the URL. The fragment of code below combines the two previous fragments (pseudocode and token encoding), completing the URL-encoding part of this case-study. It is assumed that the necessary variable declarations have been done (they are omitted below to save space). After the loop has completed, the variable url_encoded contains the result.

Get URL and URL Parts in JavaScript, JavaScript can access the current URL in parts. like https://css-tricks.com/blah/​blah/blah/index.html, you can split the string on “/” characters Returns the path of the URL. 2: public String getQuery() Returns the query part of the URL. 3: public String getAuthority() Returns the authority of the URL. 4: public int getPort() Returns the port of the URL. 5: public int getDefaultPort() Returns the default port for the protocol of the URL. 6: public String getProtocol() Returns the protocol of the URL. 7

Comments
  • Possible duplicate of Access GET directly from JavaScript?
  • @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
  • If you are looking for improvements of an existing solution, take a look at codereview.stackexchange.com.
  • @rob.m if people are confused as to what you are trying to say, consider clarifying the question.
  • probably the first of the duplicates is coming from <?php echo getAddress(); ?>
  • @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.
  • 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
  • Your duplication issue is not being caused by any of the code in your question. It's likely in your PHP getAddress() function.
  • @yeah I know, removed that php bit. But i still need to repopulate it..
  • 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.
  • @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?
  • @TylerRoper for my case, the order will always be that one. Do you have any other way to do it? Thanks
  • @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.
  • @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?