The CreatorCon Call for Content is officially open! Get started here.

How to convert String to Array

shaik_irfan
Tera Guru

Hi,

 

Currnetly i am getting an output as output = abcd, efgh, ijkl

which i want to convert as ["abcd","efgh", "ijkl"]

1 ACCEPTED SOLUTION

vkachineni
Kilo Sage

var inputStr = 'abcd,efgh,ijkl';
var outputStr = inputStr.split(',');

var strArr = [];

for(var i = 0; i < outputStr.length; i++) {
strArr.push('"' + outputStr[i] + '"');
}

strArr.join();
gs.info(inputStr);
gs.info(strArr);

*** Script: abcd,efgh,ijkl
*** Script: "abcd","efgh","ijkl"

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

12 REPLIES 12

Ankur Bawiskar
Tera Patron
Tera Patron

Hi Shaik,

where are you getting those values?

when you get those values one by one you can push those into an array and you would get the desired output

Mark Correct if this solves your issue and also mark Helpful if you find my response worthy based on the impact.
Thanks
Ankur

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

James Bengel
Giga Expert

If all you're trying to do is convert a comma separated list of strings to an array, the Javascript .split() method will do that for you without doing anything further.

var strList = 'abcd, efgh, ijkl';
var strArray = strList.split(',');
console.log('list: '+ strList + ' array: ' + strArray);
for (i = 0; i < strArray.length; i++) {
    console.log("strArray["+i+"]: " + strArray[i]);
}

This will almost get it done, but since you have spaces embedded in your list, the actual output may not be exactly what you expect. To wit:

node splitExample.js
list: abcd, efgh, ijkl array: abcd, efgh, ijkl
strArray[0]: abcd
strArray[1]: efgh
strArray[2]: ijkl

Now you could trim each string and push it to an array as seen in other examples here, or you could use the .replace() method in conjunction with .split() to remove the spaces in the string prior to parsing like this:

var strList = 'abcd, efgh, ijkl';
var strArray = strList.replace(/ /g,'').split(',');
console.log('list: '+ strList + ' array: ' + strArray);
for (i = 0; i < strArray.length; i++) {
    console.log("strArray["+i+"]: " + strArray[i]);
}

And that gives us this output:  NOte that the original string is unchanged, but the elements of the array that results are trimmed.

list: abcd, efgh, ijkl array: abcd,efgh,ijkl
strArray[0]: abcd
strArray[1]: efgh
strArray[2]: ijkl

For your reference, I recommend:

https://www.w3schools.com/jsref/jsref_split.asp

https://www.w3schools.com/jsref/jsref_replace.asp

Dianah
Tera Contributor

Get the string.
Create a character array of the same length as of string.
Traverse over the string to copy character at the i'th index of string to i'th index in the array.
Return or perform the operation on the character array.

 

Regards,

Will