简体   繁体   中英

Uncaught TypeError: Cannot read property 'toString' of null

I have this message: "Uncaught TypeError: Cannot read property 'toString' of null" while running the code below. Any help would be appreciated since I am not familiar with Javascript

Thank you in advance.

 function getUrlVars() { var arrGamePath = document.referrer; if(arrGamePath) { var reg = new RegExp("[/][a-zA-Z]{2}-[a-zA-Z]{2,4}[/]"); var locale = reg.exec(arrGamePath) .toString(); while (locale.indexOf("/") != -1) { locale = locale.replace("/", ""); } return locale; }else{ return false; } } if(getUrlVars()) { sCID = getUrlVars(); }

Your regex doesn't match and so returns null . null doesn't have a method toString() . So you should check for a match first and if it doesn't match, return false (or do whatever else you want to do - or change your regex so that it matches)

function getUrlVars() {
    var arrGamePath = document.referrer;
    if(arrGamePath) {
        var reg = new RegExp("[/][a-zA-Z]{2}-[a-zA-Z]{2,4}[/]");
        var matches = reg.exec(arrGamePath);
        if (!matches) return false;
        var locale = matches.toString();
        while (locale.indexOf("/") != -1) {
            locale = locale.replace("/", "");
        }
        return locale;
    }else{
        return false;
    }
}

if(typeof getUrlVars == 'function') {
    sCID = getUrlVars();
}

Also you are calling the function twice, once in your if line, ignoring the result:

if (getUrlVars())

and then if the if returns true, again. Just check if its type is a function instead.

So this error is related to the null property which while you did not declare a null property, that is what you are getting back as @baao shared in the first answer.

So whenever you try to access a property under a value of null or undefined in JavaScript and try to read any property, call any function on it, you get an error message: cannot read properties of null, reading toString(), so that's what's going on behind the scenes that's why you are getting an error.

You are trying to call toString() on matches which is currently null or was null .

In the modern world of TypeScript you could probably solve that like so:

const reg: null || string = new RegExp("[/][a-zA-Z]{2}-[a-zA-Z]{2,4}[/]");

And that might indicate, hey this reg variable is either a string or it might be null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM