I’ll start right away by saying that I am not a programmer but I do like to poke around things and learn. Here’s what I have:
1) URL in the following format: http://site.com/#!/show/me/stuff/1-12/
2) jQuery pagination script that outputs the # of available pages. Each number is a link with href="#pageNumber"
3) jQuery script that binds to all pagination links. The function code is below.
Basically, my goal is to replace 1-12 in my URL with the proper values if, say, I select page #2.
Here’s what I cooked up that works but is extremely ugly:
var pageId = this.href.split("#")[1];
// this gets the number from the pagination link (i.e.,
// http://site.com/#2 becomes 2)
var url = location.hash.split("/");
var url = url[url.length-2];
// this is my way of extracting "1-12" from the URL :)
var showFrom = parseFloat(url.split("-")[0]); // 1
var showTo = parseFloat(url.split("-")[1]); // 12
var itemsPerPage= (showTo-showFrom)+1; // 12
var newShowTo = (itemsPerPage*pageId); // 24
var newShowFrom = (itemsPerPage*pageId)-itemsPerPage+1; // 13
var newUrl = newShowFrom+"-"+newShowTo; // 13-24
location.hash = location.hash.replace(url, newUrl);
// http://site.com/#!/show/me/stuff/1-12/ now becomes
// http://site.com/#!/show/me/stuff/13-24/
How can I make this more elegant and in fewer steps?
Your code is not that ugly – the variable names are self explanatory and I can assure you we have all seen things that are much worse.
Anyway, here is a way to do the same thing as you did but using regexes:
How it works:
The pattern: slash
\/, followed by one or more+digits\d, followed by a hyphen-, followed by another sequence of digits(\d+), followed by an optional?slash\/, followed by the end of the string$.The substitution: We can pass a substitution function to the replace method so that we have the replacement text depend of the replaced text. The first argument to the function is the whole match (
"/1-12/") and we ignore it (_is a convention for “ignore this”).The next arguments correspond to the captured patterns in the regex – those things wrapped by parenthesis. In your case, the arguments are the string representations of the numbers for the start and the end of the range.
I then just use the same logic as you did, except that
In the end all the regex was get rid of the string splitting and streamline the code a bit. However, in a real situation I would probably try to think about a more robust solution that did not depend on fragile string operations on the URL.