1

I know that there are a lot of similar questions posted regarding Uncaught TypeError: Cannot read property 'match' of undefined, but I'm just not having much success finding a solution within any of them for my issue specifically.

The goal of this script is to take the current page URL, use regex to filter out the query string, find all links on the page, assess whether or not they contain a ?, and append the query string accordingly.

I had success with my testing on CodePen, however, when I implemented the script on a web page it failed and returned Uncaught TypeError in the console.

$(document).ready(function(){
    var myRegexp = /\?([^]*)/gm;
    var string_match = myRegexp.exec(window.location.href);

    $('a').each(function(){
        var href = $(this).attr('href');
        href += (href.match(/\?/) ? '&' : '?') + string_match[1];
        $(this).attr('href', href);
    });
});

The error flags at .match(/\?/) ? '&' : '?') + string_match[1];, so I'm...just lost at this point. Why does it only work in code playgrounds?

The original code that I modified came from here.
See the code working on CodePen here.

Any help is greatly appreciated, thank you!

DXC
  • 27
  • 8

1 Answers1

1

It seems evaluation happened on undefined href. May be you want to put defensive coding to check if href is truthy and then evaluate match on it. OR you can simply return on undefined href and not do anything.

$(document).ready(function(){
    var myRegexp = /\?([^]*)/gm;
    var string_match = myRegexp.exec(window.location.href);

    $('a').each(function(){
        var href = $(this).attr('href');
        href += href && (href.match(/\?/) ? '&' : '?') + string_match[1];
        $(this).attr('href', href);
    });
});
Rikin
  • 5,351
  • 2
  • 15
  • 22