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

is a substring of

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 '';  
    return results[1];

// say link is link1
var link = document.createElement('a');
link.href = ''
// 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
Like it.? Share it:

Comments are closed.