Search code examples
regexstringgoogle-apps-scriptformatting

How to split string in a specific order using Google Apps Script?


I am new with Google apps script and trying to learn day by day. I apologize for my basic knowledge. I am trying to split a string in a specific way. Here is the string in an array:

var data = [call number="7203266298" duration="0" date="1646769239639" type="2" presentation="1" subscription_id="89148000007344410028" post_dial_digits="" subscription_component_name="com.android.phone/com.android.services.telephony.TelephonyConnectionService" readable_date="Mar 8, 2022 12:53:59 PM" contact_name="(Unknown)"]

Now I want to split this text in the following format:

var data = [call number="7203266298",
duration="0",
date="1646769239639",
type="2",
presentation="1", 
subscription_id="89148000007344410028",
subscription_component_name="com.android.phone/com.android.services.telephony.TelephonyConnectionService",
readable_date="Mar 8, 2022 12:53:59 PM", 
contact_name="(Unknown)"]

I tried to use split() function like this:

data = data.split(" ")

But the output from this method is not really what I need, it creates unnecessary partitions like this:

[ , , call, number="+12532250046", duration="0", date="1646851016349", type="3", presentation="1", subscription_id="89148000007344410028", post_dial_digits="", subscription_component_name="com.android.phone/com.android.services.telephony.TelephonyConnectionService", readable_date="Mar, 9,, 2022, 11:36:56, AM", contact_name="(Unknown)", ]

Any guidance would be much appreciated.


Solution

  • One way of achieving this could be to combine array indexes in new array that you want to see in combination. For example:

    var temp = [call number="7203266298" duration="0" date="1646769239639" type="2" presentation="1" subscription_id="89148000007344410028" post_dial_digits="" subscription_component_name="com.android.phone/com.android.services.telephony.TelephonyConnectionService" readable_date="Mar 8, 2022 12:53:59 PM" contact_name="(Unknown)"];
    temp = temp.split(" ");
    
    newData = [temp[0]+" "+temp[1], temp[2],temp[3],temp[4],temp[5],temp[6], temp[7],temp[8],temp[9]+" "+temp[10]+" "+temp[11]+" "+temp[12]+" "+temp[13], 
    temp[14]];
    
    Logger.log(newData);
    
    Output:
    
    [call number="7203266298", duration="0", date="1646769239639", type="2", presentation="1", subscription_id="89148000007344410028", post_dial_digits="", subscription_component_name="com.android.phone/com.android.services.telephony.TelephonyConnectionService", readable_date="Mar 8, 2022 12:53:59 PM", contact_name="(Unknown)"]