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

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.


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]
}

You can use an if statement to check if the match is null like the other answers have mentioned.

Or you can use the logical or operator to get it onto one line and make it cleaner e.g.

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

You get a Type error because when the match is false the function returns null and you cannot access index 1 of null as it is not an array.

null[1] causes a type error

By using the logical OR operator || the domain variable is set to second condition when the first condition is falsey.

So when the match is false the result defaults to an empty array [] and you can access any index of an empty array without getting an error and it results in undefined

This will make domain = undefined when the match is false.

I really wish type errors weren't a problem in JS especially with objects. I seem to have add a lot of if statement and extra code every other line just to deal with type errors.

Tags:

Javascript