为什么 属性 'match' 未定义? (将查询字符串附加到页面链接)

Why is property 'match' undefined? (Appending query strings to page links)

我知道有很多关于 Uncaught TypeError: Cannot read property 'match' of undefined 的类似问题,但我只是没有成功地找到其中任何一个专门针对我的问题的解决方案。

这个脚本的目标是获取当前页面URL,使用正则表达式过滤掉查询字符串,找到页面上的所有链接,评估它们是否包含? , 并相应地附加查询字符串。

我在 CodePen 上的测试取得了成功,但是,当我在网页上执行脚本时,它失败了,并在控制台中返回 Uncaught TypeError

$(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);
    });
});

.match(/\?/) ? '&' : '?') + string_match[1]; 处的错误标志,所以我...此时迷路了。为什么它只适用于代码操场?

我修改的原代码来自here.
查看在 CodePen 上运行的代码 here

非常感谢任何帮助,谢谢!

似乎评估发生在未定义的 href 上。可能您想进行防御性编码以检查 href 是否为真,然后对其进行评估匹配。或者你可以简单地 return on undefined href 而什么都不做。

$(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);
    });
});