regex replace not replacing (google apps script)

10,807

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.

The str.replace does not change the string, where as returns a new string with the replace. Hence you may want to write something like

var regex = new RegExp('(,\\s)([A-Z]{2}")', 'gi');
var replacedData = attachmentData.replace(regex,'$2');

Note

You can drop the first capture group as

var regex = new RegExp(',\\s([A-Z]{2}")', 'gi');
var replacedData = attachmentData.replace(regex,'$1');
Share:
10,807
mulliweht
Author by

mulliweht

Updated on June 15, 2022

Comments

  • mulliweht
    mulliweht almost 2 years

    I am writing a google apps script that pulls the content from a CSV file in a gmail attachment. I need to split the csv data into several an array (with each row being it's own array). I've got all that down.

    My problem is this: One of the values in the CSV is a "City, St" format. So when I split the array using string.split(',') I end up with an extra "column." My idea to fix this was to back up and kill that comma in the initial string. Here's the relevant portion of my code:

        var attachments = msgs[i][j].getAttachments();
        for (var k = 0; k < attachments.length; k++) {
          var attachmentData = attachments[k].getDataAsString();
          var regex = new RegExp('\,\s(?:[A-Z]{2}\")', 'gi');
          attachmentData.replace(regex,' ');
    ...
    

    So what I'm trying to do is just find a comma, followed by a space, followed by exactly two letters, then a quotation mark. I want to just replace the comma with a space. I've also tried

          var regex = new RegExp('(\,\s)([A-Z]{2}\")', 'gi');
          attachmentData.replace(regex,$2);
    

    with no luck. Here's a random sample of the (very long) data string I'm running this on:

    Voice,Incoming,(###) ###-####,(###) ###-####,,,,"Dallas, TX",12/12/2014,06:26 PM,Phone Call,Voicemail,00:00:27,$0.000,-,, ,Incoming,(###) ###-####,,###,,,"Dallas, TX",12/12/2014,06:26 PM,Phone Call,Voicemail,00:00

    Can anyone see what I'm not seeing as to why this isn't working? (Or have any ideas of a better way to do this?)