Skip to content Skip to sidebar Skip to footer

Getting The Url Parameters Inside The Html Page

I have a HTML page which is loaded using a URL that looks a little like this: http://localhost:8080/GisProject/MainService?s=C&o=1 I would like to obtain the query string para

Solution 1:

A nice solution is given here:

functionGetURLParameter(sParam)
{
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) 
    {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) 
        {
            return 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');`

Solution 2:

//http://localhost:8080/GisProject/MainService?s=C&o=1const params = newURLSearchParams(document.location.search);
const s = params.get("s");
const o = params.get("o");
console.info(s); //show Cconsole.info(o); //show 1

Solution 3:

Let's get a non-encoded URL for example:

https://stackoverflow.com/users/3233722/pyk?myfirstname=sergio&mylastname=pyk

Packing the job in a single JS line...

urlp=[];s=location.toString().split('?');s=s[1].split('&');for(i=0;i<s.length;i++){u=s[i].split('=');urlp[u[0]]=u[1];}

And just use it anywhere in your page :-)

alert(urlp['mylastname']) //pyk
  • Even works on old browsers like ie6

Solution 4:

Assuming that our URL is https://example.com/?product=shirt&color=blue&newuser&size=m, we can grab the query string using window.location.search:

const queryString = window.location.search;
 console.log(queryString);
 // ?product=shirt&color=blue&newuser&size=m

We can then parse the query string’s parameters using URLSearchParams:

const urlParams = newURLSearchParams(queryString);

Then we call any of its methods on the result.

For example, URLSearchParams.get() will return the first value associated with the given search parameter:

const product = urlParams.get('product')
 console.log(product);
 // shirtconst color = urlParams.get('color')
 console.log(color);
 // blueconst newUser = urlParams.get('newuser')
 console log(newUser);
 // empty string

Other Useful Methods

Post a Comment for "Getting The Url Parameters Inside The Html Page"