Uncaught TypeError: Cannot read property '1' of null(…) in a JavaScript function

后端 未结 3 1060
青春惊慌失措
青春惊慌失措 2021-02-09 10:56

This method is part of a module; And despite the error...

Uncaught TypeError: Cannot read property \'1\' of null(…)

works to a small degree, howeve

3条回答
  •  鱼传尺愫
    2021-02-09 11:02

    String#match returns either null (no match) or an array with the matches.

    var domain = link.href.match(/(https?:\/\/.+?)\//)[1];
    //                     ^^^^^
    

    Workaround with check

    var domain = link.href.match(/(https?:\/\/.+?)\//);
    
    if (domain) {
        // do something with domain[1]
    }
    

提交回复
热议问题