I have a working code in JS for my Web Application, which generates custom-format report ID number with the pattern NSAA-####-####-YYYY, where AA - any letter, #### any number, YYYY current year. This function in JS is quoted below.
I was asked to try to transfer the same functionality to Google sheet, as a "custom function."
Although most of the code works fine, I get issues with indexOf
methods in GAS and overall I am not sure if I am doing it correctly at all. Would appreciate a quick hint on this.
This is JS code I am trying to reproduce in Apps Script:
let d = new Date();
const randomString = (length, chars) => {
let mask = '';
if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (chars.indexOf('#') > -1) mask += '0123456789';
let result = '';
for (let i = length; i > 0; --i) result += mask[Math.round(Math.random() * (mask.length - 1))];
return result;
}
// Inserting report ID into appropriate fields
const reportNS = () => {
let reportIDNS = document.getElementById("reportIDNS");
reportIDNS.value = 'NS' + randomString(2, 'A') + '-' + randomString(4, '#') + '-' + randomString(4, '#') + '-' +
d.getFullYear();
}
My first idea was to put it in someting like this:
/**
*/
var d = new Date();
function randomString (length, chars) {
var mask = '';
if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (chars.indexOf('#') > -1) mask += '0123456789';
var result = '';
for (var i = length; i > 0; --i)
result += mask[Math.round(Math.random() * (mask.length - 1))];
return result = 'NS' + randomString(2, 'A') + '-' + randomString(4, '#') + '-' + randomString(4, '#') + '-' + d.getFullYear();
}
However, I get the error
TypeError: Cannot call method "indexOf" of undefined.
Would appreciate a hint on this!
Got it - here how it works. Of course - need to use the second function to call that randomString:
// Funciton to create ReportID (or caseID) as the customer wants
function CaseID () {
var d = new Date();
var caseID = 'ID' + randomString(2, 'A') + '-' + randomString(4, '#') + '-' + randomString(4, '#') + '-' + d.getFullYear();
return caseID;
}
// Function that generates randomString - no surprises here
function randomString (length, chars) {
var mask = '';
if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (chars.indexOf('#') > -1) mask += '0123456789';
var result = '';
for (var i = length; i > 0; --i) {
result += mask[Math.round(Math.random() * (mask.length - 1))]
};
return result;
}
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.