How to convert this string to an array in ServiceNow server side script

Snehal13
Kilo Sage
 
7 REPLIES 7

OlaN
Giga Sage
Giga Sage

Hi,

Not really sure about what you want help with in this question, but you can try something like this perhaps.

var text = 'How to convert this string to an array in ServiceNow server side script';
var arrayText = [];
arrayText = text.split(' ');

gs.info('array length: ' + arrayText.length);
for (var i=0; i< arrayText.length; i++){
    gs.info('Part ' + i + ' of the array: ' + arrayText[i]);
}

/* Output:
*** Script: array length: 13
*** Script: Part 0 of the array: How
*** Script: Part 1 of the array: to
*** Script: Part 2 of the array: convert
*** Script: Part 3 of the array: this
*** Script: Part 4 of the array: string
*** Script: Part 5 of the array: to
*** Script: Part 6 of the array: an
*** Script: Part 7 of the array: array
*** Script: Part 8 of the array: in
*** Script: Part 9 of the array: ServiceNow
*** Script: Part 10 of the array: server
*** Script: Part 11 of the array: side
*** Script: Part 12 of the array: script

*/

Sandeep Rajput
Tera Patron
Tera Patron

@Snehal13 though you didn't share any string but here I am sharing a sample code using which you can convert a coma separated string to array in a script.

var fruits = 'apple,oranges,graps,banana';
var fruitsArray = fruits.split(',');
gs.info(fruitsArray);

 

 

Community Alums
Not applicable

davidwarner007
Tera Contributor

To convert a string to an array in ServiceNow server-side script, you can use the split() method. The split() method

["apple", "banana", "orange"]

You can adjust the separator parameter of the split() method to fit your specific use case...