skip to Main Content

I would like to skip an iteration of code if, the data in a cell does not match a string – number – number format. For example, the desired format is Apple-34-56. If the array that I defined has a format such as Apple-Grape-23, or any other variation contrary to the desired format, it should skip to the next iteration.

function populateData (sheet1, sheet2) {

    var dataRange = sheet1.getRange("A:A").getValues();

    for (var i = 0; dataRange.length; i++) {

        if (dataRange !== string-number-number) {
            continue;
        }
    }
}

Is this the proper way to set up the condition?

2

Answers


  1. What you are asking for is a regular expression to match your desired constraints.

    I.e. if you meant "(any-length word)-(any-length number)-(any-length number)" your if statement would become:

    if (! dataRange[i].match(/^w+-d+-d+$/)) {...};
    // (Notice the `[i]` I guess you missed 😉)
    

    That being said, you can even avoid the continue statement an make which are your targeted inputs even more clear:

    const re_fmt = /^w+-d+-d+$/;
    
    function populateData (sheet1, sheet2) {
    
        var dataRange = sheet1.getRange("A:A").getValues();
    
        for (
            let i = 0;
            dataRange.length;
            i++
        ) if (
            dataRange[i].match(re_fmt)
        ) {
    
            /* Your code... */
    
        }
    }
    
    Login or Signup to reply.
  2. A quick easy solution:

    function populateData(sheet1, sheet2) {
        var dataRange = sheet1.getRange("A:A").getValues();
    
        for (var i = 0; i < dataRange.length; i++) {
            var cellValue = dataRange[i][0]; // Accessing the value of the cell
    
            // Splitting the cell value into parts using "-"
            var parts = cellValue.split("-");
    
            // Checking if the cell value has the desired format: string-number-number
            if (parts.length === 3 && !isNaN(parts[1]) && !isNaN(parts[2])) {
                // Proceed
            } else {
                // Skip this iteration if the format doesn't match
                continue;
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search