Replace the field separator in a CSV file with Javascript

For a node project, I wanted to replace the field separator in a CSV from a comma to a tab. I thought about different solutions and finally, I came up with this neat little regex. This regex can be used to replace a delimiter in a csv file but also other usage cases are possible.

The script below replaces a comma in a csv file which uses a quote as a text delimiter and a comma as a field seperator. In some csv files text delimiters are also used for numeric values (e.g. “1”,”2″). The regex below searches for the text delimiter and then searches for the field seperator. When the field seperartor is found it replaces it with the new field seperator.

1 thought on “Replace the field separator in a CSV file with Javascript

    • Author gravatar

      var regex = new RegExp(“(“+d.t+”|^)((\\d*”+d.of+”)+)(“+d.t+”|\\d*$)”, “gmi”);

      var replaceDelimiter = csv.replace(regex,(a) => a.replace(new RegExp(d.of,”gmi”),`${}`));
      document.getElementById(‘output’).value = replaceDelimiter;

Leave a Reply

Your email address will not be published. Required fields are marked *