Last active
August 29, 2015 14:05
-
-
Save leite/58714cd01c8a029cd379 to your computer and use it in GitHub Desktop.
compare uri & query string in javascript ...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @xxleite under [BeerWare] license | |
function parse_qs(fullpath) { | |
var splitted_path = fullpath.split('?'); | |
var re = /[&\?]?([^=&?$?]+)=?([^&?$?]*)/ig, list = { | |
path:splitted_path[0].replace(/(.*\/)([^$]*)/g, '$2'), | |
qs:{}, iqs:{}}, res = [], current = ''; | |
while(res = re.exec(splitted_path[1])) { | |
if(res[1].slice(-2) == '[]') { | |
current = res[1].slice(0, -2); | |
if(list.qs[current]) { list.qs[current].push(res[2]); list.iqs[current][res[2]] = true; | |
} else { list.qs[current] = [res[2]]; list.iqs[current] = {}; list.iqs[current][res[2]] = true; } | |
} else { list.qs[res[1]] = res[2]; } | |
} | |
return list; | |
} | |
function compare_url(url1, url2) { | |
var _url1 = ('string' == typeof url1) ? parse_qs(url1) : url1; | |
var _url2 = parse_qs(url2); | |
var quality = 0; | |
// | |
if(_url2.path == _url1.path) { ++quality; } | |
for(key in _url2.qs) { | |
if(!(_url1.qs[key] && _url1.qs[key])) { continue; } | |
++quality; | |
if(!(typeof(_url1.qs[key]) == 'object' && typeof(_url2.qs[key]) == 'object')) { | |
if(_url1.qs[key] == _url2.qs[key]) { ++quality; } | |
continue; | |
} | |
++quality; | |
for(var z = 0; z < _url2.qs[key].length; ++z) { | |
if(_url1.iqs[key][ _url2.qs[key][z] ]) { | |
quality += .1; | |
} | |
} | |
} | |
return quality; | |
} | |
var main_url = "/wp-admin/edit.php?post_type=page&page_template[]=page-templates/familia.php&page_template[]=page-templates/nnnn.php&page_template[]=page-templates/vvvv.php"; | |
var comparables = [ | |
"/wp-admin/edit.php?post_type=page", | |
"/wp-admin/edit-tag.php?post_type=page", | |
"/wp-admin/edit.php?post_type=page&page_template=page-templates/familia.php", | |
"/wp-admin/edit.php?post_type=page&page_template[]=page-templates/familia.php&page_template[]=page-templates/nnnn.php", | |
"/wp-admin/facebook.php?donothing=yeah" | |
]; | |
var main_url_obj = parse_qs(main_url); | |
for(var t = 0; t < comparables.length; ++t) { | |
console.log( compare_url(main_url_obj, comparables[t]) ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment