Regex that replaces newline with comma, double quoted strings replaced with comma

developthewebz Source

I am working on a string validation. Essentially, I want new lines to be replaced with a comma, but I also want text that is inside of double quotes to maintain the space in between..

For example, if my input into a textarea is the following (in between the lines):

A "B C" D

E 123

F 456

I want it to output -> A,B C,D,E 123,F 456

In my AngularJS service, I can use this.stringReplace(styleStr, '\n', ','); to replace new lines, and then the Regex I have for my double quote validation is this: styleStr.replace(/ +(?=([^"\\]*(\\.|"([^"\\]*\\.)*[^"\\]*"))*[^"]*$)|^(?!\n)*$/g, ',').replace(/"/g, ',');

...where my stringReplace function is this:

   stringReplace: function (string, text, by) {
      // Replaces text with by in string
      var strLength = string.length,
        txtLength = text.length;
      if ((strLength === 0) || (txtLength === 0)) {
        return string;
      var i = string.indexOf(text);
      if ((!i) && (text !== string.substring(0, txtLength))) {
        return string;
      if (i === -1) {
        return string;
      var newstr = string.substring(0, i) + by;
      if (i + txtLength < strLength) {
        newstr += this.stringReplace(string.substring(i + txtLength, strLength), text, by);
      return newstr;

Currently, the first line (A "B C" D) formats correctly, but the whitespace in between E 123 is removed, as well as the whitespace in between F 456. Where am I going wrong?



comments powered by Disqus