Assistance Needed with Script for Unique Group Name Generation in ServiceNow

Saurav Bhardwa2
Tera Contributor

Hello,

I am trying to write a script for our ongoing integration. We have groups in the "Abc" application, and their names start as "143 GS <Name> SPO". We are storing these group names in ServiceNow in a custom table called <u_groups>.

We send these group names to a custom app "Abc" via integration from ServiceNow catalog tasks, where they are included in the task description for creation in that custom app. However, sometimes the same group name can appear multiple times in the description. I need a logic to check in the custom table in SNOW if the same group name exists. If it does, it should add a number in between, like "143 GS1 <Name> SPO", then "143 GS2 <Name> SPO", and so on.

I can write a script to check if the group name already exists in the custom table, but I am having trouble implementing the numbering logic.

Thank you for your help.

2 REPLIES 2

Ankur Bawiskar
Tera Patron
Tera Patron

@Saurav Bhardwa2 

for increasing the number you should split with space and then pick 2nd element from array and get the number from it and then increment

sample script. I believe this should be enough for you to start and complete. enhance as per your requirement now

var val = '143 GS1 Ankur SPO';

var arr = val.split(' ');

var prefixValue = arr[1];

var regex = /\d+/;

var onlyNumber = prefixValue.match(regex);

var onlyText = prefixValue.substring(0,prefixValue.indexOf(onlyNumber));

var newNumber = parseInt(onlyNumber) + 1;

var finalValue = arr[0] + ' ' + onlyText + newNumber + ' ' + arr[2] + ' ' + arr[3];

gs.info(finalValue);

Output with above script:

 

incremet number.gif

If my response helped please mark it correct and close the thread so that it benefits future readers.

 

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Community Alums
Not applicable

Hi @Saurav Bhardwa2 ,

Please try below code 

var str = '143 GS3 <Name> SPO';
var gr = new GlideRecord('table');
gr.addQuery('group_name', str);
gr.query();
if (gr.next()) {
    var arr = str.split(' ');
    var preName = arr[1];
    var newWord = preName.substr(0, 2);
    var num = preName.substr(2);
    var addNum = parseInt(num) + 1;
    var fullword = newWord + addNum;
    var newStr = arr[0] + " " + fullword + " " + arr[2] + " " + arr[3];
    gs.print(newStr);
}

 

Result 

SarthakKashyap_0-1716208712693.png

 

Please mark my answer correct and helpful if this works for you

Thanks and Regards

Sarthak