JavaScript Strip Out the Query String

One of the common issues with client-side web development is routing the user using the query string. The most common example is probably the sorting of data sets.

Typically if a user wants to view things by date instead of alphabetically, they’ll click on a drop down to select their preferred sorting order. Then you catch their selection and update the query string to read something like “http://www.mysite.com/data?sort=date” so that your code understands how to reorder the data.

Dealing with the query string in JavaScript has generally been a pain for me because you can get the full URL with window.location and you can get the query string with window.location.search, but then it’s up to you to fiddle with the strings to chop off the query string from the full URL. While this seems like a trivial thing to do in the grand scheme of client-side development, I always find myself grimacing when faced with the task.

However, today I managed to come up with a succinct little bit of code that accomplishes exactly this:

[code language=”javascript”]

var simpleUrl = window.location.href.slice(0,
0 – window.location.search.length – 1);

[/code]

Through a crafty use of the string.slice function you can use a negative index to chop off the end of the url. This way you don’t have to check to see if there’s even a query string to chop off—no tedious substring length calculations.

Like I said before, in the grand scheme of things this task is rather small, but I’m really pleased to have a simple reliable method of accomplishing it now 🙂

Tagged with: ,
Posted in Blurbs