We Recommend

Pro JavaScript Techniques Pro JavaScript Techniques
Pro JavaScript Techniques is the ultimate JavaScript book for the modern web developer. It provides everything you need to know about modern JavaScript, and shows what JavaScript can do for your web sites. This book doesn't waste any time looking at things you already know, like basic syntax and structures.


Posted By

jrharshath on 02/14/09


Tagged

url javascript parse


Versions (?)


Who likes this?

2 people have marked this snippet as a favorite

Anothnio
umang_nine


Javascript URL Parser


Published in: JavaScript 


URL: http://jrharshath.wordpress.com/

This is a script that can parse a URL string, and return all components in a systematic way via an object. This script is very useful in places where you want to link to a page "dynamically" generated by javascript. This is usually done by adding GET-like params after a # in the URL.

This parser can parse URLs like:

* http://jrharshath.com/
* http://jrharshath.com/page?param=value
* http://jrharshath.com/page?param=value&param2=value2
* http://jrharshath.com/some?serverparam=somevalue#JSFeature?param=val&param2=val2
* http://jrharshath.com/some?serverparam=somevalue#AjaxPage?param=val&param2=val2#AnotherAjaxFeature?featureparam=featureval
  1. /*
  2.  * Javascript URL Parser
  3.  * @author jrharshath (http://jrharshath.wordpress.com/)
  4.  * @description Parses any URL like string and returns an array or URL "Components"
  5.  *
  6.  * Working demo located at http://jrharshath.qupis.com/urlparser/
  7.  * While using in a webapp, use "urlparse(window.location.href)" to parse the current location of the web page
  8.  * Free to use, just provide credits.
  9.  */
  10. function urlparse( str )
  11. {
  12. var arr = str.split('#');
  13.  
  14. var result = new Array();
  15. var ctr=0;
  16. for each( part in arr )
  17. {
  18. var qindex = part.indexOf('?');
  19. result[ctr] = {};
  20. if( qindex==-1 )
  21. {
  22. result[ctr].mid=part;
  23. result[ctr].args = [];
  24. ctr++;
  25. continue;
  26. }
  27. result[ctr].mid = part.substring(0,qindex);
  28. var args = part.substring(qindex+1);
  29. args = args.split('&');
  30. var localctr = 0;
  31. result[ctr].args = new Array();
  32. for each( val in args )
  33. {
  34. var keyval = val.split('=');
  35. result[ctr].args[localctr] = new Object();
  36. result[ctr].args[localctr].key = keyval[0];
  37. result[ctr].args[localctr].value = keyval[1];
  38. localctr++;
  39. }
  40. ctr++;
  41. }
  42. return result;
  43. }

Report this snippet 

You need to login to post a comment.