简体   繁体   中英

search() method not working in Google Scripts

Update : Ok this was a simple fix. I selected the column of numbers I was inputting, and went to Format -> Number -> Plain Text, and all of a sudden my function worked! If I change it to Format -> Number -> Normal or anything else, it threw an error.


I have a method that adds zeros to a start of a string if it's less than 9. I'm getting an error that the function search is undefined, as in issn.search on line 4. What could possibly be causing this problem? Specifically, the error in Google Apps Script is TypeError: Cannot call method "search" of undefined. (line 5) TypeError: Cannot call method "search" of undefined. (line 5)

function fixissn(issn){
    //Logger.log("Old issn is " + issn);
    //if there's a dash in the ISSN, it need 9 characters instead of 8
    if (issn.search("-") > -1) {
        var mis = 9; 
    } else if (issn.search("-") == -1) {
        var mis = 8; 
    }

    //if the ISSN is less than 9 or 8 (mis), add zeros to the beginning
    while (issn.length < mis && issn.length > 0) {
        //zero added to beginning of ISSN
        issn = 0 + issn
    }
    //Logger.log("fixed to new issn " + issn);
    return issn;
}

Just to echo what @epascarello stated, it looks like a value is not being passed in. It is hard to say but it might be due to you using this function on a range of cells, some of which are empty. To bypass that issue you might try something like:

function fixissn(issn){
    if (issn !== undefined) {
        //Logger.log("Old issn is " + issn);
        //if there's a dash in the ISSN, it need 9 characters instead of 8
        if (issn.search("-") > -1) {
            var mis = 9; 
        } else if (issn.search("-") == -1) {
            var mis = 8; 
        }

        //if the ISSN is less than 9 or 8 (mis), add zeros to the beginning
        while (issn.length < mis && issn.length > 0) {
            //zero added to beginning of ISSN
            issn = 0 + issn
        }
        //Logger.log("fixed to new issn " + issn);
    }
    return issn;
}

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