Jquery History Plugin With Regular Expressions

Over the past couple months, I have delved into the world of jquery, which, for the uninitiated, is the framework for developing javascript in today’s world of web development. Jquery shortens or eliminates many of the more tedious aspects of HTML’s dom framework, while allowing elegant access to the fancier effects of javascript. One of the other coolest parts of this framework is the growing number of plugins built by the community.

The plugin that I want to bring up is the history plugin by Klaus Hartl, the original of which can be found here. Javascript usually has problems with the back button, but here it is integrated smoothly, and without forcing the page to do an ugly reload. As an added bonus, the plugin also allows the creation of links that are tied to an internal javascript state. Basically, javascript would now have the abilities of a full-blown 90s style html-only webpage, with the smoothness and efficiency of not requiring any page reloads. A good example of a similar javascript history module in action is Gmail, where the back button works smoothly, and you are able to copy and paste the url to a different window.

My slightly modified version of the script can be found here. This potentially interesting enhancement allows the use of a regular expression when defining the javascript internals for the history plugin. It is useful when the site has additional user-specific variables, such as an id or an object name or number, and the programmer has no desire to explicitly code every possibly imaginable scenario. Regular expressions are very powerful tools.

To use the modified version of the module, use a snippet like this one, substituting a regex for where the history module would normally require a string:

[sourcecode language="python"] $.ui.history('add', '(\\d+)/analyze/queries', function(url, pg) { set_phrasegroup(pg); //do something something }); [/sourcecode]

Note the slight irregularity where you need to escape each slash with another slash.

The first parameter, url as passed into the function is the entire string that the user inputed. It would look something like 3/analyze/queries, while pg, any other further passed parameters refer to any of the matched groups within the regex. In this case, we only have one, (\d+), a number.