Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment Alphabet characters to next character using JavaScript

I am beginner in script programming and I would like to write a script in order to have an automatic ID (date+Uppercase characters).

The script is OK without the function IF. However, I still get some issues with my script. I don't succeed to increment the character with the condition of function IF.

function onFormSubmit(e) {

//Déclaration des variables
var SheetResponse = SpreadsheetApp.getActiveSheet();
var DerniereLigne =  SpreadsheetApp.getActiveSheet().getLastRow();
var DateToday = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'ddMMYY');

//Intégration du suffixe alphabétqiue pour l'ID
// If cells value (A.n)=(A.n-1) then character of cells "N.n" is incremented until "Z" (with n is number of LastRow)
if (SheetResponse.getRange(DerniereLigne,2).getValue() == SheetResponse.getRange(DerniereLigne-1,2).getValue()) {
        var AlphaNumber = SheetResponse.getRange(DerniereLigne-1,15).getValue().charCodeAt(0);
        var NextCode = AlphaNumber + 1;
        // Si Code (Z) alors restart to "A"
        if (NextCode > 90) {nextCode = 65;}
        var NextAlpha = String.fromCharCode( NextCode );
        }
// If not cells (N.n) is set to "A"
else {NextAlpha = "A";}

//Création de l'ID dans la derniére ligne et colonne "N"
SheetResponse.getRange(DerniereLigne,14).setValue(DateToday + NextAlpha);
SheetResponse.getRange(DerniereLigne,15).setValue(NextAlpha);

}

Please, Could someone help me. Thank you in advance.

like image 919
Mohamed H Avatar asked Mar 11 '26 12:03

Mohamed H


1 Answers

Here is a function that returns the next string in lexicographic order: 'A' -> 'B' -> ... 'Z' -> 'AA' -> 'AB' -> 'AC' -> ... 'AZ' -> 'BA' -> 'BB' -> ... 'ZZ' -> 'AAA' etc.

function nextString(str) {
    if (! str)
        return 'A'  // return 'A' if str is empty or null

    let tail = ''
    let i = str.length -1
    let char = str[i]
    // find the index of the first character from the right that is not a 'Z'
    while (char === 'Z' && i > 0) {
        i--
        char = str[i]
        tail = 'A' + tail   // tail contains a string of 'A'
    }
    if (char === 'Z')   // the string was made only of 'Z'
        return 'AA' + tail
    // increment the character that was not a 'Z'
    return str.slice(0, i) + String.fromCharCode(char.charCodeAt(0) + 1) + tail

}

like image 174
mbl Avatar answered Mar 13 '26 03:03

mbl