-2

I am trying to get query parameters from the URL in javascript. I tried window.location.search and got the params but it happens only the first time I access the URL. Afterwards it is returning empty.

I read somewhere that it is due to Asynchronous GET request. So how to get parameters always from the URL in javascript?

Max Peng
  • 2,879
  • 1
  • 26
  • 43
raja
  • 1
  • 1
    Your assumption is incorrect. `location.search` will always work, unless the location changes. – SLaks Sep 20 '17 at 14:27
  • So why is it returning mixed results? Sometimes i am getting the params and sometimes i don't? – raja Sep 20 '17 at 14:29
  • have you tries window.location.hash - https://developer.mozilla.org/en-US/docs/Web/API/Location –  Sep 20 '17 at 14:30
  • Possible duplicate of [How can I get query string values in JavaScript?](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – bated Sep 20 '17 at 15:35

3 Answers3

0

This might can help for you.

var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
};
And this is how you can use this function assuming the URL is,
http://dummy.com/?technology=jquery&blog=jquerybyexample.

var tech = getUrlParameter('technology');
var blog = getUrlParameter('blog');
Kunvar Singh
  • 1,779
  • 2
  • 13
  • 21
0
function Myfunction(myvar){
  var urls = myvar;
  var myurls = urls.split("?id="); //will return the parameter after "?"
  var mylasturls = myurls[1];
  var mynexturls = mylasturls.split("&");
  var url = mynexturls[0];
  alert(url)
 }
Jesse
  • 59
  • 9
0

You can use the new javascript APIs, URL and URLSearchParams

var link = new URL('https://google.com.ec?q=blable%20bli&q=2312&dog=true')
var params = link.searchParams
var keys = [...new Set([...params.keys()])]

console.log('keys: ', keys)

for (var key of keys)
    console.log(key, params.getAll(key))
Fernando Carvajal
  • 1,869
  • 20
  • 19