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

后端 未结 3 1192
青春惊慌失措
青春惊慌失措 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:13

    Per string.match():

    Return value

    An Array containing the entire match result and any parentheses-captured matched results; null if there were no matches.

    The regular expression should match the string, as well as the protocol and domain like you have it (i.e. the grouping surrounded by parentheses (https?:\/\/.+?)). You can ensure that the return value is not null (so it should be an array) and that is has more that one element before attempting to access index 1 (since the 1st index should be 0) like this:

    var matches = link.href.match(/(https?:\/\/.+?)\//);
    if (matches !== null && matches.length > 1) {
    

    So take a look at this example:

    function match(link) {
        var matches=link.href.match(/(https?:\/\/.+?)\//);
        if (matches !== null && matches.length > 1) {
            var protocolAndDomain = matches[1];
              console.log('protocol and domain: ',protocolAndDomain );
        }
        else {
              console.log('no matching protocol and domain');
        }
    }
    var link = { href: 'stackoverflow.com'};
    match(link); //should find no matches
    
    var link2 = { href: 'https://domain.com/'};
    match(link2); //should match https://domain.com

    I use the term protocol and domain because the expression is looking for the protocol (i.e. https://) before the domain. For more information about the parts of the URL, refer to this MDN page.

提交回复
热议问题