-1

Is it possible that my change function ignore words in " "? By ignore I mean that it doesn't remove spaces in " "

Currently function outputs:

Input:

te s s sdg gdg sdg "gh hh"

Output:

te,s,s,sdg,gdg,sdg,"gh,hh"

I want:

te,s,s,sdg,gdg,sdg,gh hh

Code:

function change() {
    var data = $("#data").val();

    var dataArr= [];
    var reg1 = /\s+/g;
    var reg2 = /;+/g;
    var reg3 = /•+/g;
    var reg4 = /^-+\s*/;
    var regex= [reg1,reg2,reg3,reg4];
    
    regex.forEach(function(i) {
        data= data.replace(i, ",");
        dataArr= data.split(",");
    });
    
    $("#data").val(data);
    
}
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
laxytt
  • 5
  • 6
  • With a regex, yes. However, if you also want escape characters for the `"`s, it'll be more complex. – FZs Apr 16 '21 at 08:37
  • 1
    Does this answer your question? [Regex for splitting a string using space when not surrounded by single or double quotes](https://stackoverflow.com/questions/366202/regex-for-splitting-a-string-using-space-when-not-surrounded-by-single-or-double) – Nick Apr 16 '21 at 08:58

2 Answers2

2

You could use a pattern with a capture group, and based on the groups, replace the , with a space or return the capture inside the double quotes.

"([^"]+)"|\s+

Regex demo

const s = `te s s sdg gdg sdg "gh hh"`;
console.log(s.replace(/"([^"]+)"|\s+/g, (m, g1) => g1 ? g1 : ","));

If you don't only want to replace - only at the start of the string, you can list all the characters in a character class that you want to replace with a comma.

"([^"]+)"|[\s;•-]+
  • "([^"]+)" Match ", capture 1+ times any char between the double quotes in group 1 and match " again
  • | Or
  • [\s;•-]+ Match 1+ times any of the listed characters in the character class

const s = `te s s ;;- s•dg gdg sdg "gh hh"`;
console.log(s.replace(/"([^"]+)"|[\s;•-]+/g, (m, g1) => g1 ? g1 : ","));
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
1

You can use

function change() {
    var data = $("#data").val();

    var dataArr = [];
    var reg1 = /"([^"]*)"|\s+/g;
    var reg2 = /;+/g;
    var reg3 = /•+/g;
    var reg4 = /^-+\s*/;
    var regex= [reg1,reg2,reg3,reg4];

    regex.forEach(function(i) {
        data= data.replace(i, (_,x) => x || ",");
    dataArr= data.split(",");
    });
    $("#data").val(data);
}

The var reg1 = /"([^"]*)"|\s+/g; will match strings between double quotes and capture the part between " into Group 1, or will match one or more whitespaces.

The data= data.replace(i, (_,x) => x || ","); part will now either replace the match with , if Group 1 did not participate in the match, or with Group 1 contents.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563