Assistance Needed with Script for Unique Group Name Generation in ServiceNow
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-20-2024 05:10 AM
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.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-20-2024 05:22 AM
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:
If my response helped please mark it correct and close the thread so that it benefits future readers.
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-20-2024 05:38 AM
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
Please mark my answer correct and helpful if this works for you
Thanks and Regards
Sarthak