convert array to a pipe delimited string

nick135
Tera Expert

Hello everyone,

I have a list collector on a catalog item. When the item is submitted the Values of the field on the RITM/SCTASK appear as "a, b, c". I've been asked to convert this format to "a | b | c". so basically the ask here is to remove the comma and insert a pipe. the script I have so far looks a bit like this

//Type appropriate comment here, and begin script below
var arr = g_form.getValue('compliance');
var list;
console.log(arr);
for(var i = 0; i <= arr.length; i++) {

list += arr[i] + " | ";
console.log(list);
}
g_form.setValue('comliance_test', list);
}

 

the problem I'm having is that the list comes back up undefined, and I also end up with an extra pipe added to the end of the string. any ideas?

1 ACCEPTED SOLUTION

vkachineni
Kilo Sage
Kilo Sage
var list_comma = "abc,def,ghi";
var arr = list_comma.split(",");
var list_pipe = arr.join('|'); //join back with pipe
gs.print(list_comma);
gs.print(list_pipe);

/*
*** Script: abc,def,ghi
*** Script: abc|def|ghi
*/
Please mark Correct and click the Thumb up if my answer helps you resolve your issue. Thanks!
Vinod Kumar Kachineni
Community Rising Star 2022

View solution in original post

7 REPLIES 7

Geoff_T
Mega Sage

Hello,

Try something like:

var complianceValue = g_form.getValue('compliance');
var output = complianceValue.toString().replace(/,/g , '|');
g_form.setValue('comliance_test', output);

 

Geoff

nick135
Tera Expert

now it returns an empty string

Hmm I have tested the logic and it works. Can you log the value for:

complianceValue 

To make sure it is what you expect i.e. the comma separated string.

 

Geoff

Abhijit4
Mega Sage

Hi Nick,

Please try below,

var arr = g_form.getValue('compliance');
var newText=arr.replaceAll(',','|');
g_form.setValue('comliance_test',newText); //make sure here the field name is correct it looks to me spell mistake in field name

Let me know if you have any further queries.

Please mark this as Correct or Helpful if it helps.

Thanks and Regards,
Abhijit

By marking my response as correct or helpful, you contribute to helping future readers with similar issues.
Regards,
Abhijit
ServiceNow MVP