CHUVASH.eu

CHunky Universe of Vigouros Astonishing SHarepoint :)

Get url parameters with javascript

There is a question in Stackoverflow and this one, too. There is a fine solution for jQuery. The only thing we need is window.location.search. Say we have http://domain.com?q=hello&a=good#home, then it takes only ?q=hello&a=good, and leaves #home and the main url. Anchors can be retrieved with hash. Here are all properties of window.location:

Mozilla Firefox is the best tool to see all properties

Google Chrome provides a fine function: window.location.getParameter:

I like the name of this function. So why not to use it or create this one if a browser doesn’t have it? Well here we go:

if (!window.location.getParameter ) {
  window.location.getParameter = function() {};
}

Then I don’t want it to be depending on jQuery, eventhough the odds are big, that jQuery is there. But in all solutions I have seen, there is no usage of jQuery, so why do it as a jQuery extension?

However, we must extract the search part of window.location… I’ll use the solution of Ryan Phelan, but without jQuery (again, why extend jQuery without any usage of it?). Thanks to Johannes Milling who improved the code by making it case-insensitive.

if (!window.location.getParameter ) {
  window.location.getParameter = function(key) {
	function parseParams() {
		var params = {},
			e,
			a = /\+/g,  // Regex for replacing addition symbol with a space
			r = /([^&=]+)=?([^&]*)/g,
			d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
			q = window.location.search.toLowerCase().substring(1);

		while (e = r.exec(q))
			params[d(e[1])] = d(e[2]);

		return params;
	}

	if (!this.queryStringParams)
		this.queryStringParams = parseParams(); 

	return this.queryStringParams[key.toLowerCase()];
  };
}

I published this solution on Stackoverflow.

For us Sharepointers

In SharePoint there is actually a built-in javascript function which retrieves the url query parameters: _spGetQueryParam which can be found in init.js:

function _spGetQueryParam(p)
{ULSA13:;
	var q=window.location.search.substring(1);
	if(q && q.length > 2)
	{
		var params=q.split("&");
		var l=params.length;
		for (var i=0;i<l;i++)
		{
			var pair=params[i].split("=");
			if (pair[0].toLowerCase()==p)
				return pair[1];
		}
	}
}

As I posted in an answer on sharepoint.stackexchange.com it can be used like this:

var id = _spGetQueryParam("ID");
var url = "/Forms/AllItems.aspx?FilterField1=look&FilterValue1=" + id;
About these ads

7 responses to “Get url parameters with javascript

  1. asleb 2012-04-02 at 13:52

    How do you use this? I don’t understand how to get the url param. Do I write i.ex. parseParams(‘name’) if the URL is http://example.com/?name=bob
    This does not work. I am lost.

    • Anatoly Mironov 2012-04-02 at 14:33

      Hello asleb!

      If you add the code I provided to extend window.location object, you can just write:

      var name = window.location.getParameter("name"); //bob

      If you work with SharePoint, you can use a function from SharePoint javascript API:

       var name = _spGetQueryParam("name"); //bob
  2. asleb 2012-04-02 at 13:52

    How do I call this function?

  3. Johannes Milling 2014-09-15 at 16:24

    Hi, great post. However, there is an improvement to be done. The getParameter function above is case sensetive. Would it be possible to make it case insensitive by adding the ‘i’ character to the regex? It’s not completely easy to follow what’s happening. =)

    • Anatoly Mironov 2014-09-16 at 10:54

      Thank you for the feedback. This js code is not simple, but it is well-tuned. I took it from stackoverflow. This solution is case sensitive. If you have a solution for getting query string parameters in a case-insensitive way, I’d be thankful to get an updated version of this code.

      • Johannes Milling 2014-09-17 at 12:52

        Without changing the regex, a solution could be to simply call toLowerCase() on the key parameter and window.location.search. But that might not be the optimal solution. My guess is that making the regex case insensitive would get better performance, but I have no understanding of regex. =P

        if (!window.location.getParameter ) {
        window.location.getParameter = function(key) {
        function parseParams() {
        var params = {},
        e,
        a = /\+/g, // Regex for replacing addition symbol with a space
        r = /([^&=]+)=?([^&]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, ” “)); },
        q = window.location.search.toLowerCase().substring(1);

        while (e = r.exec(q))
        params[d(e[1])] = d(e[2]);

        return params;
        }

        if (!this.queryStringParams)
        this.queryStringParams = parseParams();

        return this.queryStringParams[key.toLowerCase()];
        };
        }

      • Anatoly Mironov 2014-09-17 at 15:22

        Thank you Johannes! I’ll update the code in my blog post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Discovering SharePoint

And having fun doing it

Bram de Jager's SharePoint blog

My view and thoughts on SharePoint.

My programming life

and everything in between

SharePoint Development Lab by @avishnyakov

It is a good place to share some SharePoint stories and development practices.

SharePoint Dragons

Nikander & Margriet on SharePoint

The Zuul Cat Idea Brewery

Where ideas on software development and entrepreneurship brew.

Paul J. Swider

Inspire! Teach! Awe!

Mai Omar Desouki - Avid SharePointer

Egyptian & Vodafoner - Senior SharePoint Consultant

Alexander Ahrens

MCPD | SharePoint | Web Development | JavaScript | .NET

Cameron Dwyer | SharePoint, Outlook, OnePlaceMail

OnePlaceMail, SharePoint, Outlook & Life's Other Little Wonders

.:paul.tavares:.

Me and My doings!

Share SharePoint Points

By Mohit Vashishtha

Jimmy Janlén "Den Scrummande Konsulten"

Erfarenheter, synpunkter och raljerande om Scrum från Jimmy Janlén

SPJoel

SharePoint for everyone

SharePointRyan.com

Ryan Dennis is a SharePoint Solutions Architect with a passion for SharePoint and PowerShell

SharePoint 2020

The Vision for a Future of Clarity

Aharoni in Unicode, ya mama

Treacle tarts for great justice

Follow

Get every new post delivered to your Inbox.

Join 232 other followers

%d bloggers like this: