Javascript: check if url is a substring of another url

If I want to find out is a url is a substring of another url, for example whether

http://blarblar.com/?abc=1

is a substring of

http://blarblar.com/?abc=1&page=2&r=3

doing a indexOf or substr wouldn’t work because there are special characters in the string. Javascript does not yet have proper library to do this, we have to either depend on 3rd party libraries or come up with our own. A simple way to do it is to split the url into 2 parts, ie pathname and query. We then need to match the pathname and query like so:

function getp(locator, name){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  
  var regexS = "[\\?&]"+name+"=([^&#]*)";  
  var regex = new RegExp( regexS );  
  var results = regex.exec( locator.href ); 
  if( results == null )    
    return '';  
  else    
    return results[1];
}

// say link is link1
var link = document.createElement('a');
link.href = 'http://blarblar.com/?abc=1'
// this is the second link, say its the original url
win = window.location;
// if the pathname is the same and param is the same, a match is found
if ((link.pathname == win.pathname) && ( getp(link, 'abc') == getp(win, 'abc'))) {
  // a match is found, do something
}

Author: bpeh

Bernard Peh is a great passioner of web technologies and one of the co-founder of Sitecritic.net Website Design and Reviews. He works with experienced web designers and developers everyday, developing and designing commercial websites. He specialises mainly in SEO and PHP programming.